Question: 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 can't do that because it will look for a property with the literal `foo->bar`, and not `bar` inside `foo`.

---

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

```
Use Xpath. It allows you to use expressions to fetch parts of an XML.

```
$xml = <<<'XML'
<?xml version="1.0" encoding="utf-8"?>
<test>
    <foo>
        <bar>Hello, World!</bar>
    </foo>
</test>
XML;

$xml = new SimpleXMLElement($xml);
$expression = 'foo/bar';

var_dump(
  (string)$xml->xpath($expression)[0]
);

```

Xpath is a really powerful tool. However to use the full potential you will have to use `DOMXpath::evaluate()`. `SimpleXMLElement::xpath()` can only return node lists as arrays of SimpleXMLElement objects. `DOMXpath:evaluate()` can return node lists or scalar values.

```
$document = new DOMDocument();
$document->loadXml($xml);
$xpath = new DOMXpath($document);
$expression = 'string(foo/bar)';

var_dump(
  $xpath->evaluate($expression)
);

```