Using xpath on a PHP SimpleXML object, SOAP + namespaces (not working..)

After researching this on SO and google for hours now… I hope to get some help here:
(I am just one step away from running a regex to remove the namespaces completely)

First this is the XML:

<?xml version="1.0" encoding="utf-16"?>
<soap:Envelope xmlns:soap="">
  <soap:Header xmlns="">
    <Security_AuthenticateReply xmlns="">

Now this is what my code in PHP looks like:

$response = simplexml_load_string( $str ,NULL, 
false, "" );
// just making sure the name space is "registered"
// but I tested all examples also with this removed
$_res = $response->xpath('//soap:Header');
/*** result: simple query for the root "soap" namespace, this looks good! (so far..)
    [0] => SimpleXMLElement Object
            [SessionId] => 0119A|1


// now we query for the "SessionId" element in the XML
$_res = $response->xpath('//soap:Header/SessionId');
/*** result: this does not return anything!

// another approach
$_res = $response->xpath('//soap:Header/SessionId/text()');
/*** result: this does not return anything at all!

// Finally, without using XPath this does work
$_res = $response->xpath('//soap:Header');
$_res = (string)$_res[0]->SessionId;
echo $_res;
/*** result: this worked

How can I get the SOAP message working with XPATH???


Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

Solution 1

The multiple namespaces are messing with it, adding the following works for me

$response->registerXPathNamespace("site", "");
$_res = $response->xpath('//site:SessionId');

also, see this previous stack overflow question

Solution 2

You need to register the default namespace used by <SessionId> element as well. Because <SessionId> is in the default namespace it does not have any prefix but in order to your XPath to work, you need to bind also this namespace to some prefix and then use that prefix in your XPath expression.

$_res = $response->xpath('//soap:Header/ns:SessionId');

XPath (1.0) expressions without a namespace prefix always match only to targets in no-namespace.

Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from or, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply