6

Evening guys.

Firstly to say, I have read 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">
  <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?

Community
  • 1
  • 1
James
  • 5,942
  • 15
  • 48
  • 72

1 Answers1

7

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">
        <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
  • 28,400
  • 5
  • 52
  • 67
  • 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 varies too much to manually put in every one. – James Jan 20 '10 at 02:49
  • Managed to fix it with a few foreach's scanning through every element ;) – James Jan 20 '10 at 03:02
  • 1
    It always slightly boggles me when people say they're converting XML into JSON without wanting to care about the structure. Why not store it as, well, XML? – IMSoP May 19 '13 at 15:08