PHP 和 XML。使用 PHP 遍历 XML 文件

标签 php xml foreach performance

我现在深陷于 foreach 炼狱中,试图想出一种使用 PHP(跟随 XML 文件内容)遍历此 XML 文件(下面的实际 XML 文本)的方法。 我正在尝试做的是以下内容:

  1. 获取所有文件夹元素名称
  2. 如果文件夹元素的子文件夹属性为 yes,则向下移动一个级别并获取该文件夹元素的名称
  3. 如果没有移动到下一个文件夹元素

画廊列表.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/

相关文章:

php - 使用 foreach 向关联数组添加一个值?

php - 在一个php脚本中使用多个数据库

c# - 如何读取一些 XML 然后在 .NET 中拆分出各种节点/元素?

java - 在displayMethod中使用printf和forEach,如何更改单个数组显示的间距

javascript - 使用带有两个参数的函数实现 JS 原生 'filter' 方法

php - Magento 获取可配置的第一个简单产品的 SKU

php - Foreach 循环无法正常工作

php - 为什么在打开的文件上取消链接成功?

c# - 使用 C# 编辑 XML 文档

未检测到 C# XElement.Load 方法?