RodrigoFW
RodrigoFW

Reputation: 11

Parse XML SOAP response php

I'm using the following code to send an request to a SOAP service:

header('Content-type: application/xml');

function doXMLCurl($url,$postXML){
    $CURL = curl_init();
    curl_setopt($CURL, CURLOPT_URL, $url); 
    curl_setopt($CURL, CURLOPT_HTTPAUTH, CURLAUTH_BASIC); 
    curl_setopt($CURL, CURLOPT_POST, 1); 
    curl_setopt($CURL, CURLOPT_POSTFIELDS, $postXML); 
    curl_setopt($CURL, CURLOPT_HEADER, false); 
    curl_setopt($CURL, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($CURL, CURLOPT_HTTPHEADER, array('Accept: text/xml','Content-Type: application/soap+xml'));
    curl_setopt($CURL, CURLOPT_RETURNTRANSFER, true);
    $xmlResponse = curl_exec($CURL); 
    return $xmlResponse;
}

$input_xml = '<s:Envelope xmlns:a="http://www.w3.org/2005/08/addressing" xmlns:s="http://www.w3.org/2003/05/soap-envelope">.....</s:Envelope>';

echo doXMLCurl('webservice_url', $input_xml);

The responde is a XML too.

How can i parse this data or convert to an array or object? I tried with simplexml_load_string() but without success.

EDIT

XML Response:

<s:Envelope xmlns:s="http://www.w3.org/2003/05/soap-envelope" xmlns:a="http://www.w3.org/2005/08/addressing">
   <s:Header>
      <a:Action s:mustUnderstand="1">...</a:Action>
   </s:Header>
   <s:Body>
      <ListStatesResponse xmlns="http://tempuri.org/">
         <ListStatesResult xmlns:b="..." xmlns:i="...">
            <b:Return>0</b:Return>
            <b:Message i:nil="true"/>
            <b:Status>00</b:Status>
            <b:ListStates>
               <b:States>
                  <b:Description>ACRE</b:Description>
                  <b:Code>AC</b:Code>
               </b:States>
               <b:States>
                  <b:Description>ALAGOAS</b:Description>
                  <b:Code>AL</b:Code>
               </b:States>
               <b:States>
                  <b:Description>AMAZONAS</b:Description>
                  <b:Code>AM</b:Code>
               </b:States>
                ...
            </b:ListStates>
         </ListStatesResult>
      </ListStatesResponse>
   </s:Body>
</s:Envelope>

Upvotes: 1

Views: 2817

Answers (2)

Pedro Lobito
Pedro Lobito

Reputation: 98971

Assuming the xml is valid, you can use SimpleXMLElement, i.e.:

$xml = new SimpleXMLElement($xmlResponse);
echo $xml->node->otherNode['Id'];

To loop it, use:

foreach ($xml->node->otherNode as $el) {
  foreach($el as $key => $val) {
   echo "{$key}: {$val}";
  }
}

Upvotes: 0

Brett
Brett

Reputation: 2010

I found the easiest way is to use json functions

$jsonObject = json_decode(json_encode($xmlString));

Then print_r($jsonObject) to find the structure. This allows attributes to be accessible to using $jsonObject->{'@attributes'}->id;

Upvotes: -1

Related Questions