> 백엔드 개발 > PHP 튜토리얼 > php轻松实现xml转化成Array

php轻松实现xml转化成Array

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
풀어 주다: 2016-06-20 13:04:59
원래의
920명이 탐색했습니다.

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으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿