0

所以我想解析这个 XML:

<?xml version="1.0" encoding="utf-8"?>
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <soapenv:Body>
    <requestContactResponse xmlns="http://webservice.foo.com">
      <requestContactReturn>
        <errorCode xsi:nil="true"/>
        <errorDesc xsi:nil="true"/>
        <id>744</id>
      </requestContactReturn>
    </requestContactResponse>
  </soapenv:Body>
</soapenv:Envelope>

具体来说,我想获取标签的值<id>

这是我尝试过的:

$dom = new DOMDocument;
$dom->loadXML($xml);
$dom->children('soapenv', true)->Envelope->children('soapenv', true)->Body->children()->requestContactResponse->requestContactReturn->id;

但我收到此错误消息:

PHP 致命错误:调用未定义的方法 DOMDocument::children()

我也尝试过使用 simpleXML:

$sxe = new SimpleXMLElement($xml);
$sxe->children('soapenv', true)->Envelope->children('soapenv', true)->Body->children()->requestContactResponse->requestContactReturn->id;

但是我收到了另一个错误消息:

PHP 致命错误:在非对象上调用成员函数 children()

我尝试过的最后一个解决方案:

$sxe = new SimpleXMLElement($xml);
$elements = $sxe->children("soapenv", true)->Body->requestContactResponse->requestContactReturn;

foreach($elements as $element) {
    echo "|-$element->id-|";
}

这次的错误信息是:

Invalid argument supplied for foreach() 

有什么建议么?

4

1 回答 1

1

这里没有记录的事实是,当您选择带有 的命名空间时->children,它对后代节点仍然有效

因此,当您询问时$sxe->children("soapenv", true)->Body->requestContactResponse,SimpleXML 假定您仍在谈论"soapenv"名称空间,因此正在寻找<soapenv:requestContactResponse>不存在的元素。

要切换回默认命名空间,您需要->children使用命名空间再次调用NULL

$sx->children("soapenv", true)->Body->children(NULL)->requestContactResponse->requestContactReturn->id
于 2012-08-20T22:37:02.510 回答