以下代码,实现将xml转换为数组的功能。
例子:
<?php /** * 转换xml为数组 * edit by www.jb200.com */ class xml { private $parser; private $tag_cur=0; private $data=array(); private $struct=array(); function xml() { $this->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 "<pre>"; 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>')); echo "</pre>"; ?>
说明:
也可以使用 simplexml_load_string函数轻松搞定。