我现在深陷于 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());
关于PHP 和 XML。使用 PHP 遍历 XML 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6837479/