Handling Custom Namespaces in SimpleXML
Question:
In an XML document with a custom namespace, SimpleXML parsing fails to expose elements from that namespace. How can this be resolved?
Answer:
To access custom namespace elements using SimpleXML, it's necessary to register and use the namespace prefix. This is typically achieved using the children() function with the namespace prefix as the first argument and true as the second argument to enable recursive matching:
<code class="php">$rss = simplexml_load_string( '<?xml version="1.0" encoding="utf-8"?> <rss version="2.0" xmlns:moshtix="http://www.moshtix.com.au"> <channel> <link>qweqwe</link> <moshtix:genre>asdasd</moshtix:genre> </channel> </rss>' ); foreach ($rss->channel as $channel) { echo 'link: ', $channel->link, "\n"; echo 'genre: ', $channel->children('moshtix', true)->genre, "\n"; }</code>
This will output:
link: qweqwe genre: asdasd
By registering the namespace prefix, it becomes possible to access custom namespace elements and retrieve their values using children().
The above is the detailed content of How to Access Elements in a Custom Namespace Using SimpleXML?. For more information, please follow other related articles on the PHP Chinese website!