解析与多个XML命名空间(Parsing XML with multiple namespaces)

2019-07-31 01:59发布

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

我也尝试使用SimpleXML的:

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

但是,我得到这个其他错误信息:

PHP致命错误:调用一个成员函数的孩子()一个非对象

最后的解决方案我已经试过:

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

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

这一次的错误信息是:

Invalid argument supplied for foreach() 

有什么建议?

Answer 1:

在这里打球的不良记录事实是,当你选择一个命名空间->children ,但它仍然在为后代节点的作用

所以,当你问$sxe->children("soapenv", true)->Body->requestContactResponse ,SimpleXML的假定你还在谈论"soapenv"命名空间,所以寻找元素<soapenv:requestContactResponse>其中不存在。

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

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


文章来源: Parsing XML with multiple namespaces