i haven't really worked with xml files before, but now i'm trying to get an xml file into a php array or object. the xml file looks like this: (it's for translating a web app)
<?xml version="1.0" ?>
<content language="de">
<string name="login">Login</string>
<string name="username开发者_C百科">Benutzername</string>
<string name="password">Passwort</string>
</content>
i tried the following:
$xml = new SimpleXMLElement("de.xml", 0, 1);
print_r($xml);
unfortunately, the values of the 'name' attribute are for some reason not in the php object. i'm looking for a way that allows me to retrieve the xml values by the name attribute.
for instance:
$xml['username'] //returns "Benutzername"
how can this be done? appreciate your help :) cheers!
This one should explain the function to you:
<?php
$xml = simplexml_load_file('de.xml');
foreach($xml->string as $string) {
echo 'attributes: '. $string->attributes() .'<br />';
}
?>
The attributes()
method from SimpleXMLElement
class will help you - http://de.php.net/manual/en/simplexmlelement.attributes.php
$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;
}
You can use an xpath expression to get the element with the name you are looking for:
(string)current($xml->xpath('/content/string[@name="username"]'))
精彩评论