Home >Backend Development >PHP Tutorial >How to Correctly Parse Namespaced XML with SimpleXML's XPath?
How to Parse XML with Namespace Using SimpleXML
Problem:
When attempting to parse XML with namespaces using SimpleXML, encountering issues with the registerXPathNamespace() method.
XML Structure:
<root xmlns:event="http://www.webex.com/schemas/2002/06/service/event"> <event:event> <event:sessionKey>...</event:sessionKey> ... </event:event> ... </root>
Example Xpath Query:
Attempting to extract 'event:sessionKey' values using:
$xml->registerXPathNamespace('e', 'http://www.webex.com/schemas/2002/06/service/event'); $event->xpath('//e:sessionKey')
Solution:
The issue lies in the necessity of both the namespace prefix ('e') and the full namespace URI in the XPath query, even without using registerXPathNamespace().
Corrected Code:
$xml = new SimpleXMLElement($r); foreach ($xml->xpath('//event:event') as $event) { var_export($event->xpath('event:sessionKey')); }
The above is the detailed content of How to Correctly Parse Namespaced XML with SimpleXML's XPath?. For more information, please follow other related articles on the PHP Chinese website!