我正试图进入位于下面SOAP中的<err:Errors>
。
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
<soapenv:Header/>
<soapenv:Body>
<soapenv:Fault>
<faultcode>Client</faultcode>
<faultstring>An exception has been raised as a result of client data.</faultstring>
<detail>
<err:Errors xmlns:err="http://www.ups.com/XMLSchema/XOLTWS/Error/v1.1">
<err:ErrorDetail>
<err:Severity>Hard</err:Severity>
<err:PrimaryErrorCode>
<err:Code>120802</err:Code>
<err:Description>Address Validation Error on ShipTo address</err:Description>
</err:PrimaryErrorCode>
</err:ErrorDetail>
</err:Errors>
</detail>
</soapenv:Fault>
</soapenv:Body>
</soapenv:Envelope>
这是我如何尝试做到这一点,但$fault_errors->Errors没有任何东西。
$nameSpaces = $xml->getNamespaces(true);
$soap = $xml->children($nameSpaces['soapenv']);
$fault_errors = $soap->Body->children($nameSpaces['err']);
if (isset($fault_errors->Errors)) {
$faultCode = (string) $fault_errors->ErrorDetail->PrimaryErrorCode->Code;
}
您可以使用XPath进行搜索:
$ns = $xml->getNamespaces(true);
$xml->registerXPathNamespace('err', $ns['err']);
$errors = $xml->xpath("//err:Errors");
echo $errors[0]->saveXML(); // prints the tree
您试图一次跳过XML中的几个步骤。->
操作符和->children()
方法只返回直接子,而不是任意的后代。
正如另一个答案中所述,您可以使用XPath向下跳转,但是如果您确实希望遍历,则需要注意所传递的每个节点的名称空间,并在它发生变化时再次调用->children()
。
下面的代码一步一步地分解它(实时演示):
$sx = simplexml_load_string($xml);
// These are all in the "soapenv" namespace
$soap_fault = $sx->children('http://schemas.xmlsoap.org/soap/envelope/')->Body->Fault;
// These are in the (undeclared) default namespace (a mistake in the XML being sent)
echo (string)$soap_fault->children(null)->faultstring, '<br />';
$fault_detail = $soap_fault->children(null)->detail;
// These are in the "err" namespace
$inner_fault_code = (string)$fault_detail->children('http://www.ups.com/XMLSchema/XOLTWS/Error/v1.1')->Errors->ErrorDetail->PrimaryErrorCode->Code;
echo $inner_fault_code, '<br />';
当然,你可以一次完成其中的部分或全部:
$inner_fault_code = (string)
$sx
->children('http://schemas.xmlsoap.org/soap/envelope/')->Body->Fault
->children(null)->detail
->children('http://www.ups.com/XMLSchema/XOLTWS/Error/v1.1')->Errors->ErrorDetail->PrimaryErrorCode->Code;
echo $inner_fault_code, '<br />';