How to access object variable name (simpleXML) using string?

I need to access a simplexml object using a string. i.e.

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

but it does not work ...

Please, help!

:)

+3
source share
3 answers

you can use links:

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

or, if you want to use the string approach, do it 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");
+1
source

You can do it like this if my memory serves me:

echo $x->{$s};
+4
source

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

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

0
source

Source: https://habr.com/ru/post/1744609/


All Articles