我现在深陷foreach炼狱的深渊,正试图想出一种方法,用php(遵循xml文件内容)遍历这个xml文件(下面是实际的xml文本)。
我要做的是:
获取所有文件夹元素名称
如果folder元素的子文件夹属性是yes,则向下移动一个级别并获取该folder元素的名称
如果不移动到下一个文件夹元素
gallerylist.xml:目录

<?xml version="1.0" encoding="ISO-8859-1"?>
<gallerylisting exists="yes">
<folder subfolder="yes">
Events
   <folder subfolder="yes">
   Beach_Clean_2010
        <folder subfolder="no">
        Onna_Village
        </folder>
            <folder subfolder="no">
            Sunabe_Sea_Wall
        </folder>
        </folder>
  </folder>
  <folder subfolder="no">
  Food_And_Drink
  </folder>
  <folder subfolder="no">
  Inside
  </folder>
  <folder subfolder="no">
  Location
  </folder>
  <folder subfolder="no">
  NightLife
  </folder>
</gallerylisting>

Gallerylisting.php网站
<?php
$xmlref = simplexml_load_file("gallerylisting.xml");
foreach($xmlref->children() as $child) {
    foreach($child->attributes() as $attr => $attrVal) {
        print $child;
        if($attrVal == "yes") {
            foreach($child->children() as $child) {
                echo $child;
                foreach($child->attributes() as $attr => $attrVal) {
                    if($attrVal == "yes") {
                        foreach($child->children() as $child) {
                            echo $child;
                        }
                    }
                }
            }
        }
    }
}

我正在…计算…5个foreach循环深入到这个php脚本中,我一点也不喜欢它,另外,如果我的文件夹有另一个子文件夹,我将不得不添加相同的
$if(attrVal=="yes")...etc.

又来了…不!无论如何,我能避免这种情况。我是php新手,尤其是php和xml。
谢谢你的帮助。

最佳答案

递归可能对你有好处。

<?php

function display_entities( $xml )
{
    foreach($xml->children() as $child) {
        foreach($child->attributes() as $attr => $attrVal) {
            print $child;
            if($attrVal == "yes") {
              display_entities( $child->children() );
            }
        }
    }
}

$xmlref = simplexml_load_file("gallerylisting.xml");

display_entities($xmlref->children());

10-05 20:46
查看更多