PHP和XML.使用PHP循环XML文件

Som*_*ica 3 php xml performance foreach

我现在正在试图通过PHP(遵循XML文件内容)来遍历这个XML文件(下面的实际XML文本).我想要做的是以下内容:

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

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>
Run Code Online (Sandbox Code Playgroud)

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;
                        }
                    }                   
                }
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我...计数... 5个foreach循环深入到这个PHP脚本中我根本不喜欢它,如果我的文件夹有另一个子文件夹,我将不得不添加这个

$if(attrVal=="yes")...etc.
Run Code Online (Sandbox Code Playgroud)

又好又好......不!无论如何,我可以避免这种情况.我是PHP的新手,特别是PHP和XML.

谢谢你的帮助.

Mr *_*ver 5

递归可能对你有益.

<?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());
Run Code Online (Sandbox Code Playgroud)