您好,欢迎访问一九零五行业门户网

php轻松实现xml转化成Array

php轻松实现xml转化成array
$obj = simplexml_load_string($s);$json = json_encode($obj);print_r(json_decode($json, true));
强烈推荐class xml { protected $pointer; public $degerler=array(); function loadstring($string){ $this->pointer = simplexml_load_string($string); return $this->pointer; } function loadfile($file){ $this->pointer = simplexml_load_file($file); return $this->pointer; } function getname(){ return $this->pointer->getname(); } function child(){ return $this->pointer->children(); } function att(){ return $this->pointer->attributes(); } function toarray(){ foreach ($this->child() as $sq){ $this->degerler[$this->getname()][$sq->getname()][] = $sq; // how many key } return $this->degerler; } }
------------------------------------
function xx($x,$p){foreach ($x as $k=>$v){if (is_object($v)) {$x[$k] = xx((array)$v,$v);}elseif (is_string($v) && $attr=$p->$k->attributes()){if ($attr) {$x[$k] = array('@attributes' => current((array)$attr),$v);}}}return $x;}$obj = simplexml_load_string($xml);print_r(xx((array)$obj,$obj));
------------------------------------
不推荐使用, 学学php正则而已。function xml2array($xml) {$xmlary = array();$reels = '/]*)\s*(?:\/>|>(.*))/s';$reattrs = '/(\w+)=(?:|\')([^\']*)(:?|\')/';preg_match_all($reels, $xml, $elements);foreach ($elements[1] as $ie => $xx) {$xmlary[$ie][name] = $elements[1][$ie];if ($attributes = trim($elements[2][$ie])) {preg_match_all($reattrs, $attributes, $att);foreach ($att[1] as $ia => $xx)$xmlary[$ie][attributes][$att[1][$ia]] = $att[2][$ia];}$cdend = strpos($elements[3][$ie], 0) {$xmlary[$ie][text] = substr($elements[3][$ie], 0, $cdend - 1);}if (preg_match($reels, $elements[3][$ie]))$xmlary[$ie][elements] = xml2array($elements[3][$ie]);else if ($elements[3][$ie]) {$xmlary[$ie][text] = $elements[3][$ie];}}return $xmlary;}
其它类似信息

推荐信息