I can not read an array

1

I have the following code

$xml = simplexml_load_string($xml_raw);
foreach ($xml->$user-agent as $ua):
    print $ua->String;
endforeach;

And it does not do anything, but print this: Notice: Undefined variable: user in /var/www/html/u.php on line 4

Notice: Use of undefined constant agent - assumed 'agent' in /var/www/html/u.php on line 4

Warning: Invalid argument supplied for foreach () in /var/www/html/u.php on line 4

    
asked by sanandresm 09.05.2016 в 16:15
source

1 answer

1

The problem is that in the XML, the tag has a name with a hyphen ( user-agent ), so you can not access that value by using the $xml->$user-agent notation. In the PHP documentation , you can find a note on this (my translation):

  

In an XML document, to access elements that contain a character not allowed in the PHP nomenclature (eg hyphens), the element name must be in quotation marks and in braces.

So what you should do is use the notation with keys, which in your case would be something like this:

$xml->{'user-agent'}
    
answered by 09.05.2016 / 16:28
source