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

时间:2012-04-27 13:41:27

标签: php xml simplexml

我一直在使用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文件 - 有人可以推荐一种方法吗?

1 个答案:

答案 0 :(得分:1)

那是因为你需要在<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'];
        }
    }
}