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;
}
相关标签:php
本文原创发布php中文网,转载请注明出处,感谢您的尊重!