Im trying to figure out the most effective way to parse som quite complicated XML using SimpleXML, and I’ve become stuck when there are namespaces in the document.
Okay, so my XML looks something like this:
<ns:event xmls:ns="http://example.com/event/1.1">
<ns:eventinfo>
<ns:start year="2011" month="9" />
<ns:eventnames>
<ns:eventname>Superevent</ns:eventname>
</ns:eventnames>
</ns:eventinfo>
<ns:eventlocale>My place</ns:eventlocale>
</ns:event>
I am able to extract the information from the “normal” tags via:
$data = simplexml_load_string($xml);
foreach ($data->children('ns', true) as $children) {
$child = $children->children('ns',true);
$eventname = ($child->eventname);
}
This would give $eventname as Superevent. However, this approach doesn’t work with attributes…
But if there wouldn’t be any namespaces, I would easily extract the attributes with for example:
$startyear = $data->$start['year'];
So – anyone got an idea to approach this problem with ease? Any info or ideas would be much appreciated.
Have you considered using SimpleXML’s xpath functionality?
edit:
What I did in the previous example was rather verbose by the way. This should probably work just as well inside the loop, as you are taking the first found nodes anyway already in the
echostatement: