skip to Main Content

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


  1. 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 …

    // Split the path into its components
    $pathComponents = explode('->', $path);
    
    // Start with the root element
    $currentElement = $xml;
    
    // Loop thru the path components and navigate thru the XML
    foreach ($pathComponents as $component) {
        if (isset($currentElement->$component)) {
            $currentElement = $currentElement->$component;
        } else {
            // You can throw an exception or handle it according to your needs
            // in this example, I just broke out of the loop
            break;
        }
    }
    
    // $currentElement should now contain the desired XML element
    

    https://www.php.net/manual/en/function.isset.php

    Login or Signup to reply.
  2. 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);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search