Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XML file to PHP array (w/attributes)

Tags:

object

php

xml

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!

like image 693
wum Avatar asked Mar 06 '26 17:03

wum


1 Answers

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

like image 61
thedom Avatar answered Mar 09 '26 09:03

thedom



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!