-2

I have an XML document and i'm using SimpleXMLElement to parse it with PHP like :

<Document>
     <Hello>
         <Name>Jason</Name>
    </Hello>
</Document>

Example to access to the name loading my XML and then i do :

$xml->Document->Hello->Name

I would like to store all this routes in associative array like

$array = [
   "Document->Hello->Name" => "name"
];

The problem is when i loop on this array my field is empty I do this :

foreach($array as $key => $v)
{
  $hereIsempty = $xml->$key
}

Is someone have a solution to get the value i want from my array mapping plz

Don't Panic
  • 41,125
  • 10
  • 61
  • 80
JasonT
  • 1
  • 1
  • The problem is, it's looking for a property named "Document->Hello->Name", which doesn't exist. It doesn't follow the arrows through the structure, it just uses that exact string. The answers here should help you with a little modification: https://stackoverflow.com/questions/41594358/how-can-i-access-a-deep-object-property-named-as-a-variable-dot-notation-in-ph – Don't Panic Jul 30 '18 at 17:16
  • Tanks you for answer but i don't really understand. Can check my post, i post my code. ty ! – JasonT Jul 30 '18 at 20:10

1 Answers1

0

Storing full route path in one key is a bad idea. if you know in advance the meaning of the path: set the tags name to const value and then use it.

But if you realy need to save path as key in array, you can separate all tags in first sub-array and set needs value as second element of array; something like this:

$needs = [];

$routes = [
    [
        'tags' => ['Document', 'Hello'], 
        'need' => 'Name'
    ]
];

foreach ($routes as $route) {
    tempXml = $xml;

    foreach ($route['tags'] as $tag) {
        $tempXml = $tempXml->{$tag};
    }

    $need[] = (string)$tempXml->{$route['need']};
}
Kart Av1k
  • 137
  • 1
  • 6