PHP - Simple XML Nested Hierarchy
I am using PHP XML function to work with XML file.
The code below works great for a simple XML hierarchy:
$xml = simplexml_load_file("test.xml");
echo $xml->getName() . "<br />";
foreach($xml->children() as $child)
{
echo $child->getName() . ": " . $child . "<br />";
}
This assumes that the structure of the XML document looks like this:
<?xml version="1.0" encoding="ISO-8859-1"?>
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>
However, if I had a more complex structure inside my XML document - the content just isn't displayed. Below is a more complex XML example:
<note>
<noteproperties>
<notetype>
TEST
</notetype>
</noteproperties>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>
I need to process XML files with undefined depth - can anyone suggest a method?
0
source to share
1 answer
This is because you need to complete one more level in <noteproperties>
Check it out for example SimpleXMLElement :: children :
$xml = new SimpleXMLElement(
'<person>
<child role="son">
<child role="daughter"/>
</child>
<child role="daughter">
<child role="son">
<child role="son"/>
</child>
</child>
</person>');
foreach ($xml->children() as $second_gen) {
echo ' The person begot a ' . $second_gen['role'];
foreach ($second_gen->children() as $third_gen) {
echo ' who begot a ' . $third_gen['role'] . ';';
foreach ($third_gen->children() as $fourth_gen) {
echo ' and that ' . $third_gen['role'] .
' begot a ' . $fourth_gen['role'];
}
}
}
+1
source to share