phpxmlsimplexml

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


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?


Solution

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