我现在深陷于foreach的炼狱中,试图想出一种使用PHP遍历这个XML文件(如下所示)的方法。我想要做的是:
- 获取所有文件夹元素的名称
- 如果文件夹元素具有子文件夹属性为yes,则向下移动一个级别并获取该文件夹元素的名称
- 否则继续下一个文件夹元素
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;
}
}
}
}
}
}
}
我现在写的PHP脚本已经使用了五个foreach循环,但我并不喜欢这种写法。而且,如果我的文件夹中再有一个子文件夹,我就得再添加同样的循环。
$if(attrVal=="yes")...etc.
再次进入,但是...不行!有没有任何方法可以避免这种情况。我对PHP和尤其是PHP和XML都很陌生。
感谢任何帮助。