PHP conversion XML for code sharing for arrays

Source: Internet
Author: User
How do you convert XML data to simple, readable array data? This article share this piece of code, can realize this function, have the need of friends to see it.

The following code implements the ability to convert XML to 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)) {$tmp 1= $tmp;            if (Is_array ($tmp 1))  {$tmp =array_merge ($tmp 1,array ($cdata));              }else{$tmp =array ($tmp 1, $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 to easily fix it.

  • 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.