PHP XMLREADER Nested Elements



Hi I am trying to use XML Reader to read some dynamic xml where I don't know the element names. I need to use XML Reader and not SimpleXML as that is all that is available on my server. The trouble I am having is trying to have something that can deal with both nested and un-nested elements. My XML looks like



<1stelement>
<2ndelement>Text</2ndelement>
<3rdelement>
<4thelement>Text</4thelement>
</3rdelement>
</1stelement>


But Could also look like:



<1stelement>Something</1stelement>


I am using the following code:



while ($reader->read()) {
if ($reader->nodeType == XMLReader::ELEMENT) {
$element = $reader->name;
//$elementarray[] = $element;
echo $element;
if ($reader->depth <1){echo"</br>";}
}

if ($reader->nodeType == XMLReader::TEXT) {
$value = $reader->value;
$valuearray[] = $value;
echo " : ".$value."</br>";
}
}


This outputs



1stElement2ndelement : text


I cannot find anyway in the poorly documented XML Reader to have the output



1stElement:
2ndelement: text


which I can populate an array with.


Any help is appreciated as I am new to PHP.


No comments:

Post a Comment