tags:

views:

58

answers:

3

i need to access a simplexml object using a string. ie.

$x->a->b = 'obj'; $s = 'a->b'; echo $x->$s;

but it doesn't seem to work...

please help!

:)

A: 

That will not work. Are you trying to use xpath?

http://www.php.net/manual/en/simplexmlelement.xpath.php

ZZ Coder
hmm i guess i could do.seems a shame that syntax doesn't work though,`$x->a = 'obj'; $s = 'a'; echo $x->$s;`works fine
significance
+1  A: 

you could use references:

$s =& $x->a->b;

or, if you want the string approach, build up the reference step by step:

function getRef($base, $str) {
    $out = $base;
    $parts = explode("->", $str);

    foreach ($parts as $p) {
        $out = $out->$p;
    }

    return $out;
}

getRef($x, "a->b");
nickf
A: 

You can do that like this, if my memory serves me:

echo $x->{$s};
mattbasta