剥离SOAP信封以保存对XML文件的响应

时间:2015-03-27 16:42:22

标签: php xml web-services soap

我有一个SOAP响应,我想保存到XML文件。当响应写入文件时,SOAP信封会随之写入,因为错误导致XML文件无效:

XML declaration allowed only at the start of the document in ...

在这种情况下,XML被声明两次:

<?xml version="1.0" encoding="ISO-8859-1"?>
    <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/">
        <SOAP-ENV:Body><ns1:NDFDgenResponse xmlns:ns1="http://graphical.weather.gov/xml/DWMLgen/wsdl/ndfdXML.wsdl">
           <dwmlOut xsi:type="xsd:string">
           <?xml version="1.0"?>
           ...

有没有一种很好的方法来删除这个SOAP信封,只是保存它之间的内容?

以下是我如何编写文件的响应:

$toWrite = htmlspecialchars_decode($client->__getLastResponse());
$fp = fopen('weather.xml', 'w');
fwrite($fp, $toWrite);
fclose($fp);

1 个答案:

答案 0 :(得分:0)

问题是htmlspecialchars_decode()。信封文档包含其他XML文档作为文本节点。如果解码XML文档中的实体,则会将其销毁。切勿在XML文档上使用htmlspecialchars_decode()

将(信封)XML加载到DOM中并从中读取所需的值。

$xml = <<<'XML'
<?xml version="1.0" encoding="ISO-8859-1"?>
<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/">
  <SOAP-ENV:Body>
    <ns1:NDFDgenResponse 
      xmlns:ns1="http://graphical.weather.gov/xml/DWMLgen/wsdl/ndfdXML.wsdl">
      <dwmlOut xsi:type="xsd:string">
        &lt;?xml version="1.0"?>
        &lt;weather>XML&lt;/weather>
      </dwmlOut>
     </ns1:NDFDgenResponse>
  </SOAP-ENV:Body>
</SOAP-ENV:Envelope>
XML;

$dom = new DOMDocument();
$dom->loadXml($xml);
$xpath = new DOMXPath($dom);
$xpath->registerNamespace('soap', 'http://schemas.xmlsoap.org/soap/envelope/');
$xpath->registerNamespace('ndfd', 'http://graphical.weather.gov/xml/DWMLgen/wsdl/ndfdXML.wsdl');

$innerXml = $xpath->evaluate(
  'string(/soap:Envelope/soap:Body/ndfd:NDFDgenResponse/dwmlOut)'
);
echo $innerXml;

输出:

<?xml version="1.0"?>
<weather>XML</weather>