【发布时间】:2011-10-13 19:52:31
【问题描述】:
我现在正沉浸在 foreach 炼狱中,试图想出一种方法来用 PHP 遍历这个 XML 文件(下面的实际 XML 文本)(遵循 XML 文件内容。) 我想做的是以下几点:
- 获取所有文件夹元素名称
- 如果文件夹元素具有“是”作为子文件夹属性,则向下移动一个级别并获取该文件夹元素的名称
- 如果不移动到下一个文件夹元素
画廊列表.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。
感谢您的帮助。
【问题讨论】:
-
当你用效率标记这个问题时,我会提出这一点。您的 xml 中不需要“子文件夹”属性。 PHP-Library 将帮助您了解该节点是否有子节点。如果有,请递归使用@Matt 的函数。您不应该将“文本”元素(例如您的文件夹名称)与节点混合。这看起来有点恶心。尝试使用“名称”属性。
-
注意以备将来参考!谢谢你的坦率! (badump ch!)
标签: php xml foreach performance