Search code examples
phpforeachsimplexml

php foreach with a variable


I'm trying to use a variable in a foreach loop (with simplexml) but am confused as to how to get it work properly.

My variable is:

$path="channel->item";

And I want my foreach to look like:

foreach ($xml->".$path." as $newsItem)

But that doesn't work - like the $path is being echo as $path rather than it's contents.

if I do:

foreach ($xml->channel->item as $newsItem) 

It works fine.
I'm sure it's just a syntax issue but I can't figure it out. Thanks in advance.


Solution

  • You can't include pointers in the variable variable.

    $members = explode('->', $path);
    foreach($xml->{$members[0]}->{$members[1]} as $v) {
    
    }
    

    This will only work if your path stays two dimensional.
    [edit] If you do need it to work recursively you can use this. Sorry took me a minute to write it:

    function pathFinder($path, $obj) {
        $members = explode('->', $path);
    
        if(is_object($obj) && count($members) && property_exists($obj, $members[0])) {
            $nextMember = $members[0];
            array_shift($members);
            return pathFinder(implode('->', $members), $obj->{$nextMember});
        } else {
            return $obj;
        }
    }
    
    $xml = new stdClass;
    $xml->channel->item[] = 'love';
    $xml->channel->item[] = 'test';
    
    $path = 'channel->item';
    $array = pathFinder($path, $xml);
    print_r($array);
    

    output:

    Array(
        [0] => love
        [1] => test
    )