0

我试图进入<err:Errors>位于下面的 SOAP 中。

<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;               
}
4

2 回答 2

1

您可以使用 XPath 进行搜索:

$ns = $xml->getNamespaces(true);
$xml->registerXPathNamespace('err', $ns['err']);

$errors = $xml->xpath("//err:Errors");
echo $errors[0]->saveXML(); // prints the tree
于 2013-03-28T14:50:35.517 回答
0

您正试图一次跳下 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 />';
于 2013-03-28T18:36:41.463 回答