Search code examples
phpxmlsoap

Extract value from xml tag in SOAP response payload


I´m trying to extract the RecordID = "1014276" from a tag

I tried with :

$result = curl_exec($ch);
curl_close($ch);

$xml2 = simplexml_load_string($result);
echo $latitude = (string) $xml2['RecordID'];

This is the XML response:

<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
   <soap:Body>
      <ns1:createDataResponse xmlns:ns1="http://3e.pl/ADInterface">
         <StandardResponse RecordID="1014276" xmlns="http://3e.pl/ADInterface"/>
      </ns1:createDataResponse>
   </soap:Body>
</soap:Envelope>

Solution

  • This involves a bit more than just accessing the attribute, first you have to select the correct element. Using XPath is the most comment way in this sort of structure. As this has a default namespace defined for the data, you will need to register this with the SimpleXMLElement first (using $xml2->registerXPathNamespace("ns1","http://3e.pl/ADInterface");.

    You can then find the element using the XPAth expression //ns1:StandardResponse. As the xpath() method returns a list of found elements, use [0] to just extract the first match. You should then be able to extract the attribute as in your code using the resultant element...

    $xml2 = simplexml_load_string($result);
    $xml2->registerXPathNamespace("ns1","http://3e.pl/ADInterface");
    
    $response = $xml2->xpath("//ns1:StandardResponse")[0];
    echo (string) $response['RecordID'];