docs.xml:
<?xml version="1.0" encoding="UTF-8"?>
<docs>
<directory name="Dir 1">
<file name="File 1" size="125" path="file1.pdf" />
<file name="File 2" size="10.2" path="file2.txt" />
</directory>
<directory name="Dir 2">
<directory name="Dir 3">
<file name="File 3" size="1887" path="file3.pdf" />
</directory>
<directory name="Dir 4">
<file name="File 4" size="475" path="file4.pdf" />
<file name="File 5" size="49" path="file4.zip" />
</directory>
</directory>
</docs>index.php:
<?php
$xml = new DOMDocument(); //建立一个DOMDocument
$xml->load('docs.xml'); //Php指定需要读取xml文件的位置$docs = $xml->getElementsByTagName('docs')->item(0);
$directory = $docs->getElementsByTagName('directory'); 
foreach ( $directory as $Content )
{
$id=$Content->getAttribute('name');
echo $id."<br/>";$files = $Content->getElementsByTagName('file');
foreach ( $files as $Concert )
{
$name = $Concert->getAttribute('name');
echo $name."<br />";
}
}
?>以上显示的结果:
Dir 1
File 1
File 2
Dir 2
File 3
File 4
File 5
Dir 3
File 3
Dir 4
File 4
File 5想要的最终结果如下:
Dir 1
 File 1
 File 2
Dir 2
 Dir 3
  File 3
 Dir 4
  File 4
  File 5应该是循环出现了问题,谁能帮忙解决一下啊,谢谢1

解决方案 »

  1.   

    用递归处理
    <?php
    $xml = new DOMDocument(); //建立一个DOMDocument
    $xml->load('docs.xml'); //Php指定需要读取xml文件的位置$docs = $xml->getElementsByTagName('docs')->item(0);
    function shownode($x) {
    foreach ($x->childNodes as $p){
    if (hasChild($p)) {
    echo $p->getAttribute('name')."<br/>";
    shownode($p);
    } elseif ($p->nodeType == XML_ELEMENT_NODE){
    echo $p->getAttribute('name')."<br/>";
    }
    }
    }
    function hasChild($p) {
    if ($p->hasChildNodes()) {
    foreach ($p->childNodes as $c) {
    if ($c->nodeType == XML_ELEMENT_NODE)
    return true;
    }
    }
    return false;
    }
    shownode($docs);
    ?>
      

  2.   

    LS正解,这个我在PHP手册里看到了.谢谢