首頁 > 後端開發 > php教程 > php轻松实现xml转化成Array

php轻松实现xml转化成Array

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
發布: 2016-06-20 13:04:59
原創
918 人瀏覽過

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
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
最新問題
怎麼學好php
來自於 1970-01-01 08:00:00
0
0
0
PHP擴充intl
來自於 1970-01-01 08:00:00
0
0
0
php數據獲取?
來自於 1970-01-01 08:00:00
0
0
0
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板