首页 > 解决方案 > 使用命名空间解析 XML 响应

问题描述

我收到无法解析的 XML 响应。事情是这样的:

<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <soap:Body>
        <soap:Fault>
            <faultcode>soap:Client</faultcode>
            <faultstring>Exception occurred</faultstring>
            <faultactor>https://services.lso.com/partnershippingservices/v1_5/PricingService.asmx</faultactor>
            <detail>
                <webServiceException xmlns="https://services.lso.com/WebServiceException/v1">
                    <code>600121</code>
                    <action>To zip code is outside of service area.</action>
                </webServiceException>
            </detail>
        </soap:Fault>
    </soap:Body>
</soap:Envelope>

这是发生错误时的响应。我想要得到的是代码和动作的价值。

我知道在正确处理请求时如何处理响应,但是当返回错误时我无能为力。

只是给你一个想法,这就是我正在做的我可以处理的响应:

$responseRate = simplexml_load_string($xmlRateResponse);
$getTotalCharge = $responseRate->children('http://schemas.xmlsoap.org/soap/envelope/')
                    ->Body->children()
                    ->EstimatePriceResponse;
$totalCharge = (float)$getTotalCharge->EstimatePriceResult->TotalCharge;
echo $totalCharge;

有了这个,我可以显示返回的费率。

任何帮助将不胜感激。谢谢。

标签: phpxmlparsingresponse

解决方案


好的,这里有一个解决方案。

$xmlResponse = new SimpleXMLElement($errorResponse);
$xmlResponse->registerXPathNamespace('soap','http://schemas.xmlsoap.org/soap/envelope/');
$result=$xmlResponse->xpath('//soap:Fault');
foreach ($result as $body) {
    echo $body->detail->webServiceException->code . "<br>";
    echo $body->detail->webServiceException->action . "<br>";
}

这将返回“ 600121”和“ To zip code is outside of service area.”,这就是我想要的。


推荐阅读