解析xml并读取php中的每个元素

时间:2012-08-08 15:37:15

标签: php xml

我有来自API的以下XML输出

<?xml version='1.0' encoding='UTF-8'?>
<Response>
    <ReturnRow Output1="11" Output2="12" Output3="13" Output4="14" Output5="15" />
    <ReturnRow Output1="21" Output2="22" Output3="23" Output4="24" Output5="25" />
    <Messages>
        <Message Code="INFO" Msg="Your request is successful." Type="APP"/>
    </Messages>       
</Response>

我正在尝试使用PHP解析上面的xml,循环子元素ReturnRown并将Output1Output2回显到HTML表格中。

这是我目前的代码:

$doc = new DOMDocument();
$doc->loadXML($test); //$test is holding the above XML
$node = $doc->getElementsByTagName( "ReturnRow" );
foreach ($node as $book) {
     var_dump($book);
}

但上述内容实际上并没有给我Ouput1Output2等的值。

我错过了什么或做错了什么?

我上面的PHP代码的结果:

object(DOMElement)#3 (18) { ["tagName"]=> string(9) "ReturnRow" ["schemaTypeInfo"]=> NULL        ["nodeName"]=> string(9) "ReturnRow" ["nodeValue"]=> string(0) "" ["nodeType"]=> int(1)     ["parentNode"]=> string(22) "(object value omitted)" ["childNodes"]=> string(22) "(object value omitted)" ["firstChild"]=> NULL ["lastChild"]=> NULL ["previousSibling"]=> string(22) "(object value omitted)" ["nextSibling"]=> string(22) "(object value omitted)" ["attributes"]=> string(22) "(object value omitted)" ["ownerDocument"]=> string(22) "(object value omitted)" ["namespaceURI"]=> NULL ["prefix"]=> string(0) "" ["localName"]=> string(9) "ReturnRow" ["baseURI"]=> string(20) "file:///W:/ischools/" ["textContent"]=> string(0) "" } object(DOMElement)#5 (18) { ["tagName"]=> string(9) "ReturnRow" ["schemaTypeInfo"]=> NULL ["nodeName"]=> string(9) "ReturnRow" ["nodeValue"]=> string(0) "" ["nodeType"]=> int(1) ["parentNode"]=> string(22) "(object value omitted)" ["childNodes"]=> string(22) "(object value omitted)" ["firstChild"]=> NULL ["lastChild"]=> NULL ["previousSibling"]=> string(22) "(object value omitted)" ["nextSibling"]=> string(22) "(object value omitted)" ["attributes"]=> string(22) "(object value omitted)" ["ownerDocument"]=> string(22) "(object value omitted)" ["namespaceURI"]=> NULL ["prefix"]=> string(0) "" ["localName"]=> string(9) "ReturnRow" ["baseURI"]=> string(20) "file:///W:/ischools/" ["textContent"]=> string(0) "" }

1 个答案:

答案 0 :(得分:2)

在您的情况下,我更愿意使用simplexml,因为它可以以易于迭代的格式返回节点的所有属性,并使用xpath查找您感兴趣的节点:

$xml = '<'.'?xml version="1.0" encoding="UTF-8"?>
<Response>
    <ReturnRow Output1="11" Output2="12" Output3="13" Output4="14" Output5="15" />
    <ReturnRow Output1="21" Output2="22" Output3="23" Output4="24" Output5="25" />
    <Messages>
        <Message Code="INFO" Msg="Your request is successful." Type="APP"/>
    </Messages>
</Response>
';

$doc = simplexml_load_string($xml);
$node = $doc->xpath('//ReturnRow');
foreach ($node as $book) {
    foreach ($book->attributes() as $name => $value) {
        var_dump((string)$name, (string)$value);
    }
}

如果您的输入始终具有这些属性,则可以在原始代码的循环中使用DOMNode的getAttribute()方法来获取值:

foreach ($node as $book) {
    var_dump($book->getAttribute('Output1'), $book->getAttribute('Output2'));
}