2012-04-27 96 views
0

我一直在使用PHP的简单XML函数来处理XML文件。PHP - 简单的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

那是因为你需要去另一个层面下来<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']; 
     } 
    } 
}