ElcompJR ElcompJR - 4 months ago 5
PHP Question

Using variables as object reference for XML

Let's say I have a XML file like this one:

<?xml version="1.0" encoding="utf-8"?>

<test>
<foo>
<bar>Hello, World!</bar>
</foo>
</test>


So, if I use something like this I can echo
Hello, World!
:

<?php
$xml = simplexml_load_file("myxml.xml");
echo $xml->foo->bar;
?>


But, what if I want to refer to
bar
with a variable?

<?php
$xml = simplexml_load_file("myxml.xml");
$reference = "foo->bar";
echo $xml->$reference;
?>


That won't work. Any solution?

Answer

You could do it like this:

$xml = simplexml_load_file("myxml.xml");

$reference = "foo->bar";
$tmp = $xml;
foreach(explode('->', $reference) as $v){
    $tmp = $tmp->$v;
}
echo $tmp;

Output:

Hello, World!



This would work even if you don't want to go until the last element. Take a look at the following example.

Test with this XML:

<?xml version="1.0" encoding="utf-8"?>

<test>
    <foo>
        <bar>Hello, World!</bar>
        <something>
            <values>
                <v1>Some value here (1)</v1>
                <v2>Some value here (2)</v2>
                <v3>Some value here (3)</v3>
                <v4>Some value here (4)</v4>
            </values>
        </something>
    </foo>
</test>

Now, change to $reference = "foo->something->values"; and from echo $tmp; to print_r($tmp);. This will be the output:

SimpleXMLElement Object
(
    [v1] => Some value here (1)
    [v2] => Some value here (2)
    [v3] => Some value here (3)
    [v4] => Some value here (4)
)