Php – parse an XML with SimpleXML which has multiple namespaces


I have this ugly XML which has alot of namespaces on it, when I try to load it with simpleXML if i indicate the first namespace I'd get an xml object ,but following tags with other namespaces would not make it to the object.

How can I parse this XML ?

<?xml version="1.0" encoding="UTF-8"?>
<soap-env:Envelope xmlns:soap-env="">
        <eb:MessageHeader xmlns:eb="" eb:version="1.0" soap-env:mustUnderstand="1">
                <eb:PartyId eb:type="URI"></eb:PartyId>
                <eb:PartyId eb:type="URI"></eb:PartyId>
            <eb:Service eb:type="compXML">theservice</eb:Service>
                <eb:MessageId>a certain messageid</eb:MessageId>
        <wsse:Security xmlns:wsse="">
            <wsse:BinarySecurityToken valueType="String" EncodingType="wsse:Base64Binary">an impresive binary security toekn</wsse:BinarySecurityToken>
        <SessionCreateRS xmlns="" version="1" status="Approved">
            <ConversationId>the goodbye token</ConversationId>

im trying to parse it with the following code

$xml = simplexml_load_string($res,NULL,NULL,"");

but the $xml object would only contain the following

SimpleXMLElement Object
    [Header] => SimpleXMLElement Object

    [Body] => SimpleXMLElement Object


Best Solution

I think you need to register the namespacing and access with XPath. Something like the following should get you going (I haven't the facility to test this).

$xml = simplexml_load_string($res, NULL, NULL, "");
$xml->registerXPathNamespace('soap-env', '');
$xml->registerXPathNamespace('eb', '');
$xml->registerXPathNamespace('wsse', '');

Then you can do something like:

foreach($xml->xpath('//eb:MessageHeader') as $header)
    var_export($header->xpath('//eb:CPAId')); // Should output 'something'.

You may not need to register the namespacing, thinking about it, as they are alredy present in the XML. Not sure on this though, would need to test.

Hope this helps.

Related Question