Php code to convert xml into an array

Source: Internet
Author: User
Php code to convert xml into an array
How can we convert xml data into simple and easy-to-read array data? The code shared in this article can implement this function. if you need it, check it out.

The following code converts xml into an array. Example:

     Parser = xml_parser_create (); xml_set_object ($ this-> parser, & $ this); xml_set_element_handler ($ this-> parser, "tag_open", "tag_close "); xml_set_character_data_handler ($ this-> parser, "cdata");} function parse ($ data) {$ this-> data = array (); $ this-> struct = array (); $ this-> tag_cur = 0; xml_parse ($ this-> parser, $ data); return $ this-> data ;} function tag_open ($ parser, $ tag, $ attributes) {$ this-> struct [] = $ tag; $ this -> Tag_cur ++;} function cdata ($ parser, $ cdata) {$ tmp = & $ this-> data; for ($ I = 0; $ I <$ this-> tag_cur; $ I ++) {if (! Isset ($ tmp [$ this-> struct [$ I]) {$ tmp [$ this-> struct [$ I] = array ();} $ tmp = & $ tmp [$ this-> struct [$ I];} if (! Empty ($ tmp) {$ tmp1 = $ tmp; if (is_array ($ tmp1) {$ tmp = array_merge ($ tmp1, array ($ cdata ));} else {$ tmp = array ($ tmp1, $ cdata) ;}} else $ tmp = $ cdata;} function tag_close ($ parser, $ tag) {array_pop ($ this-> struct); $ this-> tag_cur -- ;}}$ xml = new xml (); echo"
";  print_r($xml->parse('
      
       b1
      
      
       b2
      
      
       
        
         d1
        
        
         d1_2
        
        
         d1_3
        
       
      
      
       1
      '));  echo "
";?>

Note: You can also use the simplexml_load_string function.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.