PHP - Simple XML - Nested Hierarchy

2019-03-06 16:03发布

问题:

I have been using PHP's simple XML function to work with an XML file.

The below code works fine 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 the structure of the XML document is as follows:

<?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 within my XML document - the contents simply is not output. A more complex XML example is shown below:

<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 that have an indefinite depth - can anyone suggest a method?

回答1:

That's because you need to go another level down in <noteproperties>

Check this out, example from 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'];
        }
    }
}