I am knee deep in foreach purgatory right now trying to come up with a way to traverse this XML file (actual XML text below) with PHP(following the XML file content.) What I am trying to do is the following:
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>
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;
}
}
}
}
}
}
}
I am...counting...5 foreach loops deep into this PHP script and I do not like it at all, plus if my folders had another subfolder, I would have to add this same
$if(attrVal=="yes")...etc.
in again and well...no! Is there anyway at all that I can avoid this. I'm new to PHP, and especially PHP and XML.
Thanks for any help.
Recursion could be beneficial to you here.
<?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());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With