Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

$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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading