什么是最好的PHP DOM转换为数组函数?

5

我希望能解析XML文件,目前我发现最好的方法是使用DOMDocument()类。

示例XML字符串:

<?xml version="1.0" encoding="UTF-8" standalone="no" ?>
<response>
<resData>
<contact:infData xmlns:contact="http://example.com/contact-1.0">
<contact:status s="value1"/>
<contact:status s="value2"/>
<contact:status s="value3"/>
<contact:status s="value4"/>
</contact:infData>
</resData>
</response>

我使用下面的 dom2array 函数来解析 dom,但它只返回一个元素(仅 value4)。
<?php
    function dom2array($node) {
    $res = array();
    if($node->nodeType == XML_TEXT_NODE){
       $res = $node->nodeValue;
    }else{
       if($node->hasAttributes()){
           $attributes = $node->attributes;
            if(!is_null($attributes)){
               $res['@attributes'] = array();
               foreach ($attributes as $index=>$attr) {
                   $res['@attributes'][$attr->name] = $attr->value;
               }
           }
       }
       if($node->hasChildNodes()){
           $children = $node->childNodes;
           for($i=0;$i<$children->length;$i++){
               $child = $children->item($i);
               $res[$child->nodeName] = dom2array($child);
           }
       }
    }
    return $res;
    }
?>

有没有办法解析所有的xml元素并将它们发送到一个数组中?
输出数组:
Array
(
[response] => Array
    (
        [#text] => 

        [resData] => Array
            (
                [#text] => 

                [contact:infData] => Array
                    (
                        [#text] => 

                        [contact:status] => Array
                            (
                                [@attributes] => Array
                                    (
                                        [s] => value4
                                    )

                            )

                    )

            )

    )

)

value1、value2、value3在哪里呢?:(

谢谢。

在此处检查 xml2array 函数 - inhan
可能是重复的问题:将PHP关联数组传递到XML并从XML中传递 - hakre
1个回答

32

您可以使用这个(基于:http://php.net/manual/en/book.dom.php#93717);

function xml_to_array($root) {
    $result = array();

    if ($root->hasAttributes()) {
        $attrs = $root->attributes;
        foreach ($attrs as $attr) {
            $result['@attributes'][$attr->name] = $attr->value;
        }
    }

    if ($root->hasChildNodes()) {
        $children = $root->childNodes;
        if ($children->length == 1) {
            $child = $children->item(0);
            if ($child->nodeType == XML_TEXT_NODE) {
                $result['_value'] = $child->nodeValue;
                return count($result) == 1
                    ? $result['_value']
                    : $result;
            }
        }
        $groups = array();
        foreach ($children as $child) {
            if (!isset($result[$child->nodeName])) {
                $result[$child->nodeName] = xml_to_array($child);
            } else {
                if (!isset($groups[$child->nodeName])) {
                    $result[$child->nodeName] = array($result[$child->nodeName]);
                    $groups[$child->nodeName] = 1;
                }
                $result[$child->nodeName][] = xml_to_array($child);
            }
        }
    }

    return $result;
}

测试;

$s = '<?xml version="1.0" encoding="UTF-8" standalone="no"?>
        <response>
            <resData foo="1">
                <contact:infData xmlns:contact="http://example.com/contact-1.0" bar="1">
                    <contact:status s="value1"/>
                    <contact:status s="value2"/>
                    <contact:status s="value3"/>
                    <contact:status s="value4"/>
                </contact:infData>
            </resData>
        </response>';

$xml = new DOMDocument();
$xml->loadXML($s);
$xmlArray = xml_to_array($xml);
print_r($xmlArray);
// print_r($xmlArray['response']['resData']['contact:infData']['contact:status'][0]['@attributes']['s']);
// foreach ($xmlArray['response']['resData']['contact:infData']['contact:status'] as $status) {
    // echo $status['@attributes']['s'] ."\n";
// }

3
非常好的函数 - 但在处理 CDATA 部分时会失败。我将 if ($child->nodeType == XML_TEXT_NODE) 更改为 if (in_array($child->nodeType,[XML_TEXT_NODE,XML_CDATA_SECTION_NODE])) - But those new buttons though..
我得到了一堆(不必要的?)空的#text键 -- http://sandbox.onlinephpfunctions.com/code/26e649132b340af0dfc9953f6c2de1433bb9f8c8 - drzaus
2
为了删除空的#text键,在foreach $children循环的开头添加以下内容:if($child->nodeType == XML_TEXT_NODE && empty(trim($child->nodeValue))) continue; - drzaus
@drzaus empty(trim("0")) 将会移除 "0",使用 trim($child->nodeValue) === '' - Brad Kent

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接