Marc M.
Marc M.

Reputation: 174

Extract a value from a SOAP Response in PHP

I need to a value from this SOAP response. The value is in the loginresponse / return element. Here's the response:

<soap-env:envelope 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/">
<soap-env:body soap-env:encodingstyle="http://schemas.xmlsoap.org/soap/encoding/" xmlns:ns1="urn:DBCentralIntf-IDBCentral">
    <ns1:loginresponse>
        <return xsi:type="xsd:string"><**THIS IS THE VALUE I NEED**></return>
    </ns1:loginresponse>
</soap-env:body>

Here's how I'm trying to parse:

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

    $xml = simplexml_load_string($response, NULL, NULL, "http://schemas.xmlsoap.org/soap/envelope/");
    $ns = $xml->getNamespaces(true);
    $soap = $xml->children($ns['SOAP-ENV']);
    $res = $soap->Body->children($ns['NS1']);

    print_r($res->LoginResponse->Return);

But I get an empty object.

Thanks for your help!

Upvotes: 1

Views: 3437

Answers (2)

Don&#39;t Panic
Don&#39;t Panic

Reputation: 41810

Instead of using cURL and attempting to parse the XML response, consider using the PHP SOAP client. You may need to install PHP SOAP or enable it in your PHP configuration. (I'm using PHP on Windows, so I just had to uncomment extension=php_soap.dll in php.ini.)

If you have SOAP installed, you can get the WSDL from the provider of the web service you're using. Based on Googling this value in the XML you showed: xmlns:ns1="urn:DBCentralIntf-IDBCentral", I'm guessing you can find it here, but you'll probably have better luck finding it since you know for sure what web service you're using.

After you have the WSDL, using the PHP SOAP client is super easy:

$client = new SoapClient('path/to/your.wsdl');
$response = $client->Login(['username', 'password']);
$theValueYouNeed = $response->loginresponse->return;

Upvotes: 3

Marc M.
Marc M.

Reputation: 174

UPDATE: Removing the namespaces clears things up a bit (although a hack). Here my new code:

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

$cleanxml = str_ireplace(['SOAP-ENV:', 'SOAP:'], '', $response);
$cleanxml = str_ireplace('NS1:','', $cleanxml);
$xml = simplexml_load_string($cleanxml);

echo $xml->Body->LoginResponse->return[0];

Upvotes: 3

Related Questions