PHP SimpleXML question...iterate through each line of XML determine tag used -
im intermeediate php developer trying take first shots @ parsing through xml. understand basics, looping through nodes , printing them , attributes. 1 thing im lost on how examine , write conditions on tag names in xml document?
so need read each line of xml file:
determine if open <level>
tag , replace <ul>
determine of <file>
tag , replace <li>file</li>
determine if </level>
tag , replace </ul>
the level tags have attributes telling them apart.
the xml looks 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 looking 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 nested <level>
tags....because of cant echo <ul>
</ul>
, loop <li>
tags....i have take each element in xml file , decide tag replace with.
any great.
thanks
craig
you need create recursive function. check if there nested levels , if so, generates them same function.
note, need cast file-nodes (string) print them out!
function printlevel(simplexmlelement $e){ $re = ''; if(!empty($e->level)){ // checking nested levels foreach($e->level $lvl){ $re .= '<ul>'.printlevel($lvl)."</ul>\n"; } } if(!empty($e->file)){ // checking files foreach($e->file $file){ $re .= '<li>'.(string)$file."</li>\n"; } } return $re; } $xml = new simplexmlelement($xmltext); echo printlevel($e);
this work. xml isn't well-formed! add covering root element , replace ) >!
Comments
Post a Comment