Extracting data form XML file with SimpleXML in PHP

Posted by Cudos on Stack Overflow See other posts from Stack Overflow or by Cudos
Published on 2010-04-05T12:59:00Z Indexed on 2010/04/05 13:03 UTC
Read the original article Hit count: 208

Filed under:
|

Introduction:

I want to loop through XML files with flexible categories structure.

Problem:

I don't know to loop through a theoretical infinte subcategories without having to make x amount of "for each" statements (See coding example in the bottom). How do I dynamically traverse the categories structure?

What I have now:

I have no problem looping through XML files with a set structure:

<catalog>
    <category name="Category - level 1">
        <category name="Category - level 2">
            <category name="Category - level 3" />
        </category>
        <category name="Category - level 2">
            <category name="Category - level 3" />
        </category>
    </category>
</catalog>

Coding example:

//$xml holds the XML file
foreach ( $xml AS $category_level1 )
{
    echo $category_level1['name'];

    foreach ( $category_level1->category AS $category_level2 )
    {
        echo $category_level2['name'];

        foreach ( $category_level2->category AS $category_level3 )
        {
           echo $category_level3['name'];
        }
    }
}

© Stack Overflow or respective owner

Related posts about simplexml

Related posts about php