php - 使用命名空间解析 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;
有了这个,我可以显示返回的费率。
任何帮助将不胜感激。谢谢。
解决方案
好的,这里有一个解决方案。
$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.
”,这就是我想要的。
推荐阅读
- java - 如何从当前日期获取当前日期和接下来 30 天的日期
- plotly - Plotly 4.8,模板在应用时不添加图像布局
- sql - Distinct selection by one of values with a condition
- android - Android导航组件 - 从“任何地方”/基本片段导航?
- gatsby - 盖茨比 - 找不到模块反应
- python - 根据另一个数据帧的值替换数据帧的 NaN
- reactjs - React Native(EXPO)中通用链接中的哈希标记
- ios - UILabel 上的 Swift 动态宽度被破坏
- c# - 无法设置共享 Excel 加载项组图像
- c# - C# | 枚举排序的编译时间检查