PHP - 简单 XML - 嵌套层次结构


PHP - Simple XML - Nested Hierarchy

我一直在使用PHP的简单XML函数来处理XML文件。

下面的代码适用于简单的 XML 层次结构:

$xml = simplexml_load_file("test.xml");
echo $xml->getName() . "<br />";
foreach($xml->children() as $child)
{
    echo $child->getName() . ": " . $child . "<br />";
}

这假定 XML 文档的结构如下所示:

<?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>

但是,如果我的 XML 文档中有一个更复杂的结构 - 内容根本不输出。下面显示了一个更复杂的 XML 示例:

<note>
    <noteproperties>
        <notetype>
            TEST
        </notetype>
    </noteproperties>
    <to>Tove</to>
    <from>Jani</from>
    <heading>Reminder</heading>
    <body>Don't forget me this weekend!</body>
</note>

我需要处理具有无限深度的XML文件 - 任何人都可以建议一种方法吗?

那是因为你需要在<noteproperties>中再往下走一个层次

看看这个,例子来自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'];
        }
    }
}