3

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">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!

3 Answers 3

1

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

Sign up to request clarification or add additional context in comments.

Comments

0
$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;
}

Comments

0

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"]'))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.