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