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: 
It's because you are trying to access 3rd level in one variable. PHP couldn't handle `->` in variable.

```
$level1 = 'foo';
$level2 = 'bar';

echo $xml->$level1->$level2;

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

```