SOAP响应返回无格式单行文本,无法提取数据求原因
问题
通过PHP Curl调用SOAP接口时,返回的响应包含正确数据,但却是无空格的单行文本,无法直接提取数据,请问原因是什么?
调用代码如下:
$curl = curl_init(); curl_setopt_array($curl, array( CURLOPT_URL => "http://tempsite.com?wsdl", CURLOPT_RETURNTRANSFER => true, CURLOPT_CUSTOMREQUEST => "POST", CURLOPT_POSTFIELDS => '<soapenv:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:deal="http://tempsite.com?wsdl"> <soapenv:Header/> <soapenv:Body> <deal:check soapenv:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"> <input xsi:type="deal:Inputs"> <CNumber xsi:type="xsd:string">9863282</CNumber> <INumber xsi:type="xsd:string">IB5S4335</INumber> </input> </deal:check> </soapenv:Body> </soapenv:Envelope>', CURLOPT_HTTPHEADER => array("content-type: text/xml"), )); $response = curl_exec($curl); $err = curl_error($curl); curl_close($curl); echo $response;
预期的格式化XML响应如下:
<?xml version="1.0" encoding="UTF-8"?> <SOAP-ENV:Envelope SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/" xmlns:tns="http://wsdl"> <SOAP-ENV:Body> <ns1:CheckResponse xmlns:ns1="http://wsdl"> <return xsi:type="tns:CheckResults"> <RtnMessage xsi:type="xsd:string">OK</RtnMessage> </return> </ns1:CheckResponse> </SOAP-ENV:Body> </SOAP-ENV:Envelope>
原因分析
- 服务端输出优化:绝大多数SOAP服务端会默认压缩XML中的空白字符(换行、空格、制表符等),目的是减少传输的数据体积,提升响应速度。这是服务端的配置行为,和你的请求代码无关。
- XML语法特性:XML规范中,标签之间的空白字符属于无关紧要的内容,不影响XML的结构和数据解析。服务端返回单行压缩XML完全符合标准,只是可读性较差,但数据本身是完整正确的。
- 未指定格式化要求:SOAP协议没有强制服务端返回格式化XML,除非服务端提供了特定的请求参数或HTTP头来开启格式化输出,否则默认会返回压缩后的单行内容。
快速解决方法
如果需要格式化XML以便阅读或调试,可以用PHP内置的DOMDocument扩展处理响应:
$response = curl_exec($curl); // 处理响应 if ($response && !$err) { $dom = new DOMDocument(); $dom->preserveWhiteSpace = false; $dom->loadXML($response); $dom->formatOutput = true; echo $dom->saveXML(); }
内容的提问来源于stack exchange,提问作者roundabout100
相关产品推荐
相关产品推荐

