Search code examples
phpxmlxpathnamespacessimplexml

PHP and Simplecml_load_string and Xpath to echo specific Value


I have the below SOAP response:

<?xml version="1.0" encoding="utf-8"?>

<soap:Envelope xmlns:soap="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" xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd" xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd">

<soap:Header>
<wsa:Action>RetrieveResponse</wsa:Action>
<wsa:MessageID>urn:uuid:4bd57838-61fd-4edf-8c66-XXXXXXXX</wsa:MessageID>
<wsa:RelatesTo>urn:uuid:eaa150ab-fe7f-4b9b-855f-YYYYYYYY</wsa:RelatesTo>
<wsa:To>http://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymous</wsa:To>
<wsse:Security><wsu:Timestamp wsu:Id="Timestamp-bcd6b0b0-9fc0-45a1-9363-AAAAAA"><wsu:Created>2015-08-11T09:06:40Z</wsu:Created><wsu:Expires>2015-08-11T09:11:40Z</wsu:Expires></wsu:Timestamp></wsse:Security>
</soap:Header>

<soap:Body>
<RetrieveResponseMsg xmlns="http://exacttarget.com/wsdl/partnerAPI">
    <OverallStatus>OK</OverallStatus>
    <RequestID>12af20a5-b76e-4043-ae76-XXXXXXXX</RequestID>
    <Results xsi:type="Subscriber">
        <PartnerKey xsi:nil="true" />
        <ObjectID xsi:nil="true" />
        <EmailAddress>[email protected]</EmailAddress>
        <Status>Active</Status></Results>
    <Results xsi:type="Subscriber">
        <PartnerKey xsi:nil="true" />
        <ObjectID xsi:nil="true" />
<EmailAddress>[email protected]</EmailAddress>
<Status>Active</Status></Results>
</RetrieveResponseMsg>
</soap:Body></soap:Envelope>

I am trying to echo / store the EmailAddress from the above response so I can use it later on in the script.

What I am doing is this:

$xmlstring = $client->__getLastResponse();

// Loads the XML
$xml = simplexml_load_string($xmlstring);

//print $xml->asXML();

echo "Result:".$xml->children('http://schemas.xmlsoap.org/soap/envelope/')->Body->children('http://exacttarget.com/wsdl/partnerAPI')->Results[0]->EmailAddress;

But I keep getting this error:

Fatal error: Call to a member function children() on a non-object in

I'm really at my wits end trying to grab the EmailAddress. How can I do this?


Solution

  • The xml path is wrong, you forgot RetrieceResponseMsg.

    The correct path is:

    $xml->children("http://schemas.xmlsoap.org/soap/envelope/")->Body->children("http://exacttarget.com/wsdl/partnerAPI")->RetrieveResponseMsg->Results->EmailAddress