我正试图进入位于下面的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-&gt;错误没有任何内容。
$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;
}
答案 0 :(得分:1)
您可以使用XPath进行搜索:
$ns = $xml->getNamespaces(true);
$xml->registerXPathNamespace('err', $ns['err']);
$errors = $xml->xpath("//err:Errors");
echo $errors[0]->saveXML(); // prints the tree
答案 1 :(得分:0)
您正试图立即跳过XML中的几个步骤。 ->
运算符和->children()
方法只返回直接子项,而不是任意后代。
如另一个答案中所述,您可以使用XPath跳转,但如果您想要遍历,则需要注意所传递的每个节点的命名空间,并在其中再次调用->children()
变化。
以下代码将其逐步分解(live demo):
$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 />';