Parsing XML with nested namespaces in PHP

I received a XML with categories in it from Pohoda software from a client.
I struggled a bit with it, beacuse it contained nested namespaces what was new to me.
After figuring out it on my own I realized I could try google it and with luck I found ideas and code to reuse.

I came up with the following code to parse the XML:

$xml = file_get_contents(POHODA_CATEGORIES.xml);
$xml = simplexml_load_string($xml);
$ns = $xml->getNameSpaces(true);

foreach ($xml->xpath('//lst:categoryDetail') as $categories) {
    $ctg = $categories->children($ns['ctg']);
    foreach ($ctg->category as $category) {

        insert_page($category->id, $category->name);
        foreach ($c->subCategories->category as $subcategory) {
            insert_page($subcategory->id, $subcategory->name);
        }
    }
}

I also published a gist for it https://gist.github.com/mikaelz/288d1611eec0f80c1293

Advertisements

About Michal Zuber

Full stack developer, biker and rollerblader. Owner and developer at https://nevilleweb.sk/ Co-founded http://neville.sk/ Blog at https://michalzuber.wordpress.com/
This entry was posted in php and tagged , , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s