Forum Moderators: coopster

Message Too Old, No Replies

foreach() Inside foreach() Taxing on Memory

Checking XML Objects

         

brodyh

6:54 am on Aug 31, 2009 (gmt 0)

10+ Year Member



So, I have a script that takes an XML file that looks something like this:

<level_1> 
<level_2>
<level_3>
<level_4 date=""/>
</level_3>
</level_2>
<level_2>
<level_3>
<level_4 date=""/>
</level_3>
</level_2>
<level_2>
<level_3>
<level_4 date=""/>
</level_3>
</level_2>
</level_1>

So, let's say I need to find data in <level_4> in each <level_3>. In order to do this, I would write a PHP script like such:

foreach($XML->level_1 as $level1) { 
foreach($level1->level_2 as $level2) {
foreach($level2->level_3 as $level3) {
foreach($level3->level4 as $level4) {
echo $level4['date'];
}
}
}
}

The problem I have with this is it's extremely taxing on my server. In my actual script I am checking for new albums of multiple artists, so the more artists I have to look up on the same page, the longer that page takes to process.

I have tried something along the lines of this:

foreach ($XML->level_1->level_2->level_3->level_4 as $level4) { 
// Do whatever
}

But that fails, and I can understand why because not every array has been processed. Is there a smarter way to do this? Unfortunately the XML is coming from a REST service so I have no control over the XML itself. What's worse is that in the real script I also have to use if() statements to make sure that the date tag exists on "<level_4>".

Any help would be greatly appreciated.

coopster

11:47 am on Aug 31, 2009 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



Can you use the xpath [php.net]?

brodyh

2:25 pm on Aug 31, 2009 (gmt 0)

10+ Year Member



Actually, right after posting this I did read about that. :P