-->

PHP Parse Soap Reponse Issue - SimpleXMLElement

2019-06-08 10:06发布

问题:

I'm having problems using PHP SimpleXMLElement and simpleSMLToArray() function to parse a SOAP Response. I'm getting the SOAP response from my SOAP Server just fine. I'm writing both the SOAP Client and Server in this case. I'm using NuSoap for the server. To me, the soap response looks perfect, but the PHP5 Soap Client doesn't seem to parse it. So, as in the past, I'm using SimpleXMLElement and the function simpleXMLToArray() from PHP.NET (http://php.net/manual/en/book.simplexml.php), but can't seem to get an array.

<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="urn:eCaseWSDL">
   <SOAP-ENV:Body>
      <ns1:registerDocumentByPatientResponse xmlns:ns1="urn:eCaseWSDL">
         <returnArray xsi:type="tns:ReturnResult">
            <id xsi:type="xsd:int">138</id>
            <method xsi:type="xsd:string">registerDocumentByPatient</method>
            <json xsi:type="xsd:string">0</json>
            <message xsi:type="xsd:string">success</message>
            <error xsi:type="xsd:string">0</error>
         </returnArray>
      </ns1:registerDocumentByPatientResponse>
   </SOAP-ENV:Body>
</SOAP-ENV:Envelope>

PHP Code from my class ($this references apply to my library code).

// Define SimpleXMLElement
$xml_element = new SimpleXMLElement($response_string); // SOAP XML
$name_spaces = $xml_element->getNamespaces(true);
var_dump($name_spaces);

$soap = $xml_element->children('ns1');
var_dump($soap);

$soap_array = $this->simpleXMLToArray($soap);
var_dump($soap_array);

return $soap_array;

I can see the namespaces; ns1, etc. But, the array is not returned. SimpleXMLElement looks like it's returning an object, but empty.

<pre>array(3) {
  ["SOAP-ENV"]=>
  string(41) "http://schemas.xmlsoap.org/soap/envelope/"
  ["ns1"]=>
  string(13) "urn:eCaseWSDL"
  ["xsi"]=>
  string(41) "http://www.w3.org/2001/XMLSchema-instance"
}
object(SimpleXMLElement)#23 (0) {
}
bool(false)

Anyone have any ideas as to what I'm doing wrong. I must not have drunk enough coffee this morning. I'm tempted to just parse it with regular expressions.

回答1:

SimpleXML creates a tree object, so you have to follow that tree to get to the nodes you want.

Also, you have to use the actual namespace URI when accessing it, e.g.: urn:eCaseWSDL instead of ns1:

Try this:

$soap = $xml_element->children($name_spaces['SOAP-ENV'])
                    ->Body
                    ->children($name_spaces['ns1'])
                    ->registerDocumentByPatientResponse
                    ->children();

var_dump((string)$soap->returnArray->id); // 138