如何解析soap-php的xml响应


How to parse xml response of soap php

我需要解析soapserver的这个响应:

<?xml version="1.0" encoding="UTF-8"?><SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:wsa="http://schemas.xmlsoap.org/ws/2004/08/addressing">
 <SOAP-ENV:Header>
  <wsa:MessageID SOAP-ENV:mustUnderstand="0">uuid:5f7271f0-de19-11e1-8035-e656d1754971</wsa:MessageID>
  <wsa:To SOAP-ENV:mustUnderstand="0">http://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymous</wsa:To>
 </SOAP-ENV:Header>
 <SOAP-ENV:Body>
  <ns1:wssigatewayResponse xmlns:ns1="urn:it-progress-operate:ws_operate">
   <ns1:result xsi:nil="true"/>
   <ttOut xmlns="urn:it-progress-operate:ws_operate">
    <ttOutRow xmlns="urn:it-progress-operate:ws_operate">
     <ParPos xmlns="urn:it-progress-operate:ws_operate">0</ParPos>
     <ParNam xmlns="urn:it-progress-operate:ws_operate">ContentType</ParNam>
     <ParVal xmlns="urn:it-progress-operate:ws_operate">text/xml</ParVal>
    </ttOutRow>
    <ttOutRow xmlns="urn:it-progress-operate:ws_operate">
     <ParPos xmlns="urn:it-progress-operate:ws_operate">1</ParPos>
     <ParNam xmlns="urn:it-progress-operate:ws_operate">Result</ParNam>
     <ParVal xmlns="urn:it-progress-operate:ws_operate">200</ParVal>
    </ttOutRow>
    <ttOutRow xmlns="urn:it-progress-operate:ws_operate">
     <ParPos xmlns="urn:it-progress-operate:ws_operate">2</ParPos>
     <ParNam xmlns="urn:it-progress-operate:ws_operate">XMLDocumentOut</ParNam>
     <ParVal xmlns="urn:it-progress-operate:ws_operate">&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot; ?&gt;
&lt;DtsAgencyLoginResponse xmlns=&quot;DTS&quot; xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot; xsi:schemaLocation=&quot;DTS file:///R:/xsd/DtsAgencyLoginMessage_01.xsd&quot;&gt;&lt;SessionInfo&gt;&lt;SessionID&gt;178918&lt;/SessionID&gt;&lt;Profile&gt;A&lt;/Profile&gt;&lt;Language&gt;ENG&lt;/Language&gt;&lt;Version&gt;1&lt;/Version&gt;&lt;/SessionInfo&gt;&lt;AdvisoryInfo/&gt;&lt;/DtsAgencyLoginResponse&gt;</ParVal>
    </ttOutRow>
   </ttOut>
   <ns1:opcErrorMessage/>
  </ns1:wssigatewayResponse>
 </SOAP-ENV:Body>
</SOAP-ENV:Envelope>

如何从最后一个ttOutRow中的ParVal获取SessionID?

将SOAP响应加载到DOMDocument对象中:

$soapDoc = new DOMDocument();
$soapDoc->loadXML($soapResponse);

为该文档准备一个DOMXPath对象:

$xpath = new DOMXPath($soapDoc);

urn:it-progress-operate:ws_operate命名空间注册前缀:

$xpath->registerNamespace('operate', 'urn:it-progress-operate:ws_operate');

检索有效载荷节点:

$path = "//operate:ttOutRow[operate:ParNam='XMLDocumentOut']/operate:ParVal";
$result = $xpath->query($path);

保存有效负载XML:

$payloadXML = $result->item(0)->nodeValue;

现在您已经有了有效负载XML字符串,请再次执行该过程:

  • 将其加载到DOMDocument中
  • 准备一个DOMXpath对象
  • 注册DTS命名空间
  • 使用XPath检索值

最好将整个过程封装到一个函数中,这样您就可以重用它。