开发者

how to access an object (simpleXML) variable name using a string?

开发者 https://www.devze.com 2022-12-30 02:57 出处:网络
i need to access a simplexml object using a string. ie. $x->a->b = \'obj\'; $s = \'a->开发者_开发知识库;b\';

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!

:)


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

echo $x->{$s};


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");


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

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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号