How to pass a string from a php variable into an xml request?

59 views Asked by At

I probably composed my question very stupidly, but I did the best I could, I apologize in advance)

I have an XML file. I need to run a query like this:

$xml->shop->offers->offer

The problem is that I get this path from a variable:

$path = 'shop->offers->offer'

But it won't work like this:

$xml = simplexml_load_file('example.com');
$exampleElement = $xml->$path;

How can I fix the code so it works?

1

There are 1 answers

0
Barmar On BEST ANSWER

Split the path, then loop over it getting each nested property.

$props = explode("->", $path);
$el = $xml;
foreach ($props as $prop) {
    $el = $el->$prop;
}
var_dump($el);