我现在正陷入 foreach 炼狱中,试图想出一种用 PHP(遵循 XML 文件内容)遍历这个 XML 文件(下面的实际 XML 文本)的方法。
我想做的是:
- 获取所有文件夹元素名称
- 如果文件夹元素的子文件夹属性为 yes,则向下移动一级并获取该文件夹元素的名称
- 如果没有移动到下一个文件夹元素
画廊列表.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>
画廊列表.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());
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)