【问题标题】:Strip SOAP Envelope for Saving Response to XML File剥离 SOAP 信封以将响应保存到 XML 文件
【发布时间】:2015-06-01 02:02:46
【问题描述】:

我有一个想要保存到 XML 文件的 SOAP 响应。当响应写入文件时,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);

【问题讨论】:

    标签: php xml web-services soap


    【解决方案1】:

    问题是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>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-03-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-27
      相关资源
      最近更新 更多