Craig
Craig

Reputation: 1

PHP SimpleXML question...iterate through each line of XML determine tag used

Im an intermeediate PHP developer trying to take my first shots at parsing through XML. I understand the basics, looping through nodes and printing them and their attributes. The one thing im lost on is how do I examine and write conditions on the tag names in the XML document?

So what I need to do is read each line of the xml file:

Determine if its an open <level> tag and replace with <UL> Determine of its a <file> tag and replace it with <li>file</li> determine if its an </level>tag and replace it with </ul>

The level tags have attributes telling them apart.

The XML looks something like this

<level dirname="1">
     <file>Filename1</file>
     <file>Filename2</file>
     <file>Filename3</file>
     <file>Filename4</file>
 </level>
<level dirname="2">
     <file>Filename1</file>
     <file>Filename2</file>
     <file>Filename3</file>
     <file>Filename4</file>
 </level>
<level dirname="3">
     <level dirname = "5">
            <file>Filename1</file>
            <file>Filename2</file>
            <file>Filename3</file>
            <file>Filename4</file>
     </level>
 </level>

it should end up looking like this:

<ul>
     <li>Filename1</li>
     <li>Filename2</li>
     <li>Filename3</li>
     <li>Filename4</li>
 </ul>
<ul>
     <li>Filename1</li>
     <li>Filename2</li>
     <li>Filename3</li>
     <li>Filename4</li>
 </ul>
<ul>
     <ul>
            <li>Filename1</li>
            <li>Filename2</li>
            <li>Filename3</li>
            <li>Filename4</li>
     </ul>
 </ul>

Notice the Nested <level> tags....because of this I cant simply echo a <ul> </ul> and then loop for <li> tags....I have to take each element in the xml file and decide which tag to replace it with.

Any help would be great.

Thanks

Craig

Upvotes: 0

Views: 555

Answers (1)

Mano Kovacs
Mano Kovacs

Reputation: 1514

You need to create a recursive function. This will check if there are nested levels and if so, it generates them with the same function.

Note, that you need to cast the file-nodes with (string) to print them out!

function printLevel(SimpleXMLElement $e){
    $re = '';
    if(!empty($e->level)){ // checking for nested levels
        foreach($e->level as $lvl){
            $re .= '<ul>'.printLevel($lvl)."</ul>\n";
        }
    }

    if(!empty($e->file)){ // checking for files
        foreach($e->file as $file){
            $re .= '<li>'.(string)$file."</li>\n";
        }
    }
    return $re;
}

$xml = new SimpleXMLElement($xmlText);
echo printLevel($e);

This would work. But your XML isn't well-formed! Add a covering root element and replace ) with >!

Upvotes: 1

Related Questions