所以我想解析这个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()
有什么建议吗?
答案 0 :(得分:1)
这里记录不足的事实是,当您选择带有->children
的命名空间时,对于后代节点仍然有效。
因此,当您要求$sxe->children("soapenv", true)->Body->requestContactResponse
时,SimpleXML假设您仍在讨论"soapenv"
命名空间,因此正在寻找不存在的元素<soapenv:requestContactResponse>
。
要切换回默认命名空间,您需要再次使用->children
命名空间调用NULL
:
$sx->children("soapenv", true)->Body->children(NULL)->requestContactResponse->requestContactReturn->id