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









