views:

495

answers:

2

Evening guys.

Firstly to say, I have read http://stackoverflow.com/questions/1133897/how-do-i-parse-xml-containing-custom-namespaces-using-simplexml.

I'm parsing an XML document from a source not mind, and they use a custom namespace.

<?xml version="1.0" encoding="utf-8"?>
<rss version="2.0" xmlns:moshtix="http://www.moshtix.com.au"&gt;
  <channel>
   <item>
    <link>qweqwe</link>
    <moshtix:genre>asdasd</moshtix:genre>
...

For example. When I parse using SimpleXML, none of the mostix: namespace elements are on show or accessible. Probably a really simple solution, but any ideas guys?

A: 

How are you trying to access them? Since this seems to be the default namespace you shouldnt have to do anything special.

prodigitalson
"foreach ($xml->channel->item as $event){ echo '<pre>'; $event;" Will show all the normal items like <link> but nothing with the moshtix namespace.
James
+1  A: 

Usually, people use children().

$rss = simplexml_load_string(
    '<?xml version="1.0" encoding="utf-8"?>
    <rss version="2.0" xmlns:moshtix="http://www.moshtix.com.au"&gt;
        <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";
}
Josh Davis
While that works for extract each element, which is helpful, quite a lot of the time I need to perform a json_encode and simply bundle up each individual valid item and store them in a database. But when I do this, it doesn't recognise the custom namespace items. Any ideas? The data inside each <item> varies too much to manually put in every one.
James
Managed to fix it with a few foreach's scanning through every element ;)
James