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