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?
2
Answers
You could split the path into its components and loop through them to navigate through the SimpleXML object.
One way to do this is to use explode(). It’s a built-in PHP function used to split a string into an array of substrings based on a specified substring at which the input string will be split. In this case it could be used to split the path stored in the $path variable into an array of components, which are then used to move through the XML structure.
https://www.php.net/manual/en/function.explode.php
You could try …
https://www.php.net/manual/en/function.isset.php
Split the path, then loop over it getting each nested property.