Use PHP to convert XML into readable arrays!

Source: Internet
Author: User

The simpler and better way is to use simplexml_load_string. A function can easily solve the problem, and the effect is good!

 

Let's take a look at the following items.

 

 

Class XML {<br/> private $ parser; <br/> private $ tag_cur = 0; <br/> private $ DATA = array (); <br/> private $ struct = array (); <br/> function XML () {<br/> $ this-> parser = xml_parser_create (); <br/> xml_set_object ($ this-> parser, & $ this); <br/> xml_set_element_handler ($ this-> parser, "tag_open", "tag_close "); <br/> xml_set_character_data_handler ($ this-> parser, "CDATA"); <br/>}< br/> function parse ($ data) {<br/> $ this-> d ATA = array (); <br/> $ this-> struct = array (); <br/> $ this-> tag_cur = 0; <br/> xml_parse ($ this-> parser, $ data); <br/> return $ this-> data; <br/>}< br/> function tag_open ($ parser, $ tag, $ attributes) {<br/> $ this-> struct [] = $ tag; <br/> $ this-> tag_cur ++; <br/>}< br/> function CDATA ($ parser, $ CDATA) {<br/> $ TMP = & $ this-> data; <br/> for ($ I = 0; $ I <$ this-> tag_cur; $ I ++) <br/>{< br/> If (! Isset ($ TMP [$ this-> struct [$ I]) <br/>{< br/> $ TMP [$ this-> struct [$ I] = array (); <br/>}< br/> $ TMP = & $ TMP [$ this-> struct [$ I]; <br/>}< br/> If (! Empty ($ TMP) <br/>{< br/> $ tmp1 = $ TMP; <br/> If (is_array ($ tmp1 )) <br/>{< br/> $ TMP = array_merge ($ tmp1, array ($ CDATA )); <br/>} else {<br/> $ TMP = array ($ tmp1, $ CDATA); <br/>}< br/>} else $ TMP = $ CDATA; <br/>}< br/> function tag_close ($ parser, $ tag) {<br/> array_pop ($ this-> struct ); <br/> $ this-> tag_cur --; <br/>}</P> <p> $ xml = New XML (); <br/> echo "<PRE> "; <br/> print_r ($ XML-> parse ('<A> <A1> <B1> B1 </B1> <B2> b2 </B2> <B3> <C1> <d1> d1 </D1> <d1> d1_2 </D1> <d1> d1_3 </D1> </C1> </B3> </A1> <E1> 1 </E1> </a> ')); <br/> echo "</PRE> ";

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.