XML file to PHP array (with attributes)

I still haven't worked with xml files, but now I'm trying to get an XML file into a php array or object. The xml file is as follows: (it is for translating a web application)

<?xml version="1.0" ?>
<content language="de"> 
 <string name="login">Login</string>
 <string name="username">Benutzername</string>
 <string name="password">Passwort</string>
</content>

I tried the following:

$xml = new SimpleXMLElement("de.xml", 0, 1);
print_r($xml);

Unfortunately, the value of the 'name' attribute is for some reason not in the php object. I am looking for a way that allows me to get xml values ​​using the name attribute.

eg:

$xml['username'] //returns "Benutzername"

How can I do that? appreciate your help :) greetings!

+3
source share
3 answers

This should explain this function to you:

<?php
$xml = simplexml_load_file('de.xml');

foreach($xml->string as $string) { 
  echo 'attributes: '. $string->attributes() .'<br />';
}
?>

The method attributes()from the class SimpleXMLElementwill help you - http://de.php.net/manual/en/simplexmlelement.attributes.php

+1
$xmlStr = <<<XML
<?xml version="1.0" ?>
<content language="de"> 
 <string name="login">Login</string>
 <string name="username">Benutzername</string>
 <string name="password">Passwort</string>
</content>
XML;

$doc = new DomDocument();
$doc->loadXML($xmlStr);

$strings = $doc->getElementsByTagName('string');
foreach ($strings as $node) {
    echo $node->getAttribute('name') . ' = ' . $node->nodeValue . PHP_EOL;
}
0

xpath, , :

(string)current($xml->xpath('/content/string[@name="username"]'))
0

Source: https://habr.com/ru/post/1781129/


All Articles