如何在PHP中从XML SOAP响应中获取ResponseCode元素的值?
问题背景
给定SOAP响应内容:
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://sdsds.xmlsoap.org/soap/envelope/"> <SOAP-ENV:Body> <ns0:ServiceResponse xmlns:ns0="ababa.co.ke/Schemas/SAFService.xsd"> <ns0:ResponseHeader> <ns0:ResponseCode>1</ns0:ResponseCode> <ns0:ResponseMsg>999</ns0:ResponseMsg> </ns0:ResponseHeader> </ns0:ServiceResponse> </SOAP-ENV:Body> </SOAP-ENV:Envelope>
尝试以下两段PHP代码获取ResponseCode的值均失败:
// 无效代码1 $obj = simplexml_load_string($xml); $result = $obj->body->ServiceResponse->ResponseHeader->ResponseCode; echo $result[0]; print_r($result); // 无效代码2 $foo = new SimpleXMLElement($xml); $bar = json_decode(json_encode($foo)); print_r($bar);
错误原因排查
- 未处理XML命名空间:SOAP响应中的节点都带有命名空间前缀(
SOAP-ENV:、ns0:),SimpleXML默认不会自动识别带前缀的节点,直接用无前缀标签名访问会找不到对应节点。 - 大小写错误:XML标签区分大小写,代码中用小写
body访问SOAP-ENV:Body节点,完全不匹配。 - JSON转换丢失结构:用
json_encode转SimpleXMLElement对象时,命名空间节点会被转成带@attributes的特殊结构,破坏原有层级,无法直接通过属性链取值。
正确实现方式
方法1:通过命名空间前缀访问
$xml = '<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://sdsds.xmlsoap.org/soap/envelope/"> <SOAP-ENV:Body> <ns0:ServiceResponse xmlns:ns0="ababa.co.ke/Schemas/SAFService.xsd"> <ns0:ResponseHeader> <ns0:ResponseCode>1</ns0:ResponseCode> <ns0:ResponseMsg>999</ns0:ResponseMsg> </ns0:ResponseHeader> </ns0:ServiceResponse> </SOAP-ENV:Body> </SOAP-ENV:Envelope>'; $obj = simplexml_load_string($xml); // 获取SOAP-ENV命名空间下的Body节点 $body = $obj->children('SOAP-ENV', true)->Body; // 获取ns0命名空间下的ServiceResponse节点 $serviceResp = $body->children('ns0', true)->ServiceResponse; // 提取ResponseCode并转成字符串 $responseCode = (string)$serviceResp->ResponseHeader->ResponseCode; echo $responseCode; // 输出:1
方法2:通过完整命名空间URI访问(更可靠,避免前缀变更)
$obj = simplexml_load_string($xml); // 定义两个命名空间的完整URI $soapNs = 'http://sdsds.xmlsoap.org/soap/envelope/'; $serviceNs = 'ababa.co.ke/Schemas/SAFService.xsd'; $body = $obj->children($soapNs)->Body; $serviceResp = $body->children($serviceNs)->ServiceResponse; $responseCode = (string)$serviceResp->ResponseHeader->ResponseCode; echo $responseCode; // 输出:1
内容的提问来源于stack exchange,提问作者Jay Doshi
相关产品推荐
相关产品推荐

