正在分析具有多个命名空间的XML


Parsing XML with multiple namespaces

所以我想解析这个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() 

有什么建议吗?

这里记录不足的事实是,当您选择具有->children的命名空间时,它对派生节点仍然有效。

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

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

$sx->children("soapenv", true)->Body->children(NULL)->requestContactResponse->requestContactReturn->id