PHP: SimpleXML XPaths and Namespaces

Posted by Jetlogs @ 7:36 pm
Category: PHP, Web Development

Ever since PHP version 5.2.0, XML parsing has been made so much easier with the new SimpleXMLElement->xpath() function. No longer do we have to parse an XML document by working our way through all the child node, we just have to know the XML element’s name

Assuming we have an XML string assigned to $xml_string

$xml_string='<?xml version="1.0" encoding="utf-8"?>
<a>
	<b>
		<c>
			<d>
				<e>Hello World</e>
			</d>
		</c>
	</b>
</a>';

$xml = new SimpleXMLElement($xml_string);

Here is how it was done before 5.2.0 to access the <e> element

echo $xml->b->c->d->e[0]; //prints Hello World

Now with the new SimpleXMLElement->xpath() function, here is how it is done:

$result = $xml->xpath('//e');
echo $result[0]; //prints Hello World

However, being a new function, it comes with its own bugs and quirks. As for the timebeing, SimpleXMLElement->xpath() function doesn’t support default namespaces and will not be able to perform an XPath search on those types of documents.

The only thing that can be done right now is a simple workaround by removing the namespace attribute, or changing the namespace tag to preserve the namespace. Here is how it is done:

$xml_string='<?xml version="1.0" encoding="utf-8"?>
<a xmlns="http://www.opentravel.org/OTA/2003/05">
	<b>
		<c>
			<d>
				<e>Hello World</e>
			</d>
		</c>
	</b>
</a>';

$processed_string = str_replace("xmlns=", "ns=", $xml_string);
$xml = new SimpleXMLElement($processed_string);
$result = $xml->xpath('//e');
echo $result[0]; //prints Hello World as expected

3 Comments »

3 Comments to “PHP: SimpleXML XPaths and Namespaces”

  1. RaMa-NoOb
    1

    hope this feature is included in our server since xml is very much used in the company.. haha..

  2. Jetlogs
    2
    Author Comment

    what PHP version are you using?

  3. Developer James
    3

    Hi – I am trying to search an xml file using xpath but how can I do this with an attribute?
    Thanks

RSS Comment Feed Comments RSS |trackback TrackBack URI

Leave a comment

  • Archives

  • Donations

  • Social Bookmarks

  • Jetlogs.org
    Some Rights Reserved 2007
    Creative Commons License