xml格式数据转数组的函数

Posted dai-荣

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了xml格式数据转数组的函数相关的知识,希望对你有一定的参考价值。

方法一:

function xmlToArray($xml){
 
 //禁止引用外部xml实体
 
libxml_disable_entity_loader(true);
 
$xmlstring = simplexml_load_string($xml, ‘SimpleXMLElement‘, LIBXML_NOCDATA);
 
$val = json_decode(json_encode($xmlstring),true);
 
return $val;
 
}

 

方法二:

function xmlstr_to_array($xmlstr) {
        $doc = new \DOMDocument();
        $doc->loadXML($xmlstr);
        return domnode_to_array($doc->documentElement);
    }
 function domnode_to_array($node) {
        $output = array();
        switch ($node->nodeType) {
            case XML_CDATA_SECTION_NODE:
            case XML_TEXT_NODE:
                $output = trim($node->textContent);
                break;
            case XML_ELEMENT_NODE:
                for ($i=0, $m=$node->childNodes->length; $i<$m; $i++) {
                    $child = $node->childNodes->item($i);
                    $v = domnode_to_array($child);
                    if(isset($child->tagName)) {
                        $t = $child->tagName;
                        if(!isset($output[$t])) {
                            $output[$t] = array();
                        }
                        $output[$t][] = $v;
                    }
                    elseif($v) {
                        $output = (string) $v;
                    }
                }
                if(is_array($output)) {
                    if($node->attributes->length) {
                        $a = array();
                        foreach($node->attributes as $attrName => $attrNode) {
                            $a[$attrName] = (string) $attrNode->value;
                        }
                        $output[‘@attributes‘] = $a;
                    }
                    foreach ($output as $t => $v) {
                        if(is_array($v) && count($v)==1 && $t!=‘@attributes‘) {
                            $output[$t] = $v[0];
                        }
                    }
                }
                break;
        }
        return $output;
    }

以上是关于xml格式数据转数组的函数的主要内容,如果未能解决你的问题,请参考以下文章

php xml 和json转成Array(数组)格式和数组转成xml和json

php xml 和json转成Array(数组)格式和数组转成xml和json

PHP 数组转XML 格式

PHP 数组转XML 格式

php 怎么将数组转xml的函数

php之XML转数组函数的方法