I have an XML file in this format
"note.xml"
<currencies>
<currency name="US dollar" code_alpha="USD" code_numeric="840" />
<currency name="Euro" code_alpha="EUR" code_numeric="978" />
</currencies>
PHP CODE
$xml=simplexml_load_file("note.xml");
echo $xml->name. "<br>"; --no output
echo $xml->code_alpha. "<br>"; --no output
echo $xml->code_numeric . "<br>"; --no output
print_r($xml);
output of print_r($xml)-->SimpleXMLElement Object ( [currency] => SimpleXMLElement Object ( [@attributes] => Array ( [name] => US dollar [code_alpha] => USD [code_numeric] => 840 ) )
I didnt get any output for the ECHO statements I tried 'simplexml_load_file' and tried reading from it but it doesnt work. Please tell me what php code should I use to read from this format of XML file.
Using DomDocument:
<?php
$str = <<<XML
<currencies>
<currency name="US dollar" code_alpha="USD" code_numeric="840" />
<currency name="Euro" code_alpha="EUR" code_numeric="978" />
</currencies>
XML;
$dom = new DOMDocument();
$dom->loadXML($str);
foreach($dom->getElementsByTagName('currency') as $currency)
{
echo $currency->getAttribute('name'), "\n";
echo $currency->getAttribute('code_alpha'), "\n";
echo $currency->getAttribute('code_numeric'), "\n";
echo "+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+\n";
}
?>
Live DEMO.
Using simplexml:
<?php
$str = <<<XML
<currencies>
<currency name="US dollar" code_alpha="USD" code_numeric="840" />
<currency name="Euro" code_alpha="EUR" code_numeric="978" />
</currencies>
XML;
$currencies = new SimpleXMLElement($str);
foreach($currencies as $currency)
{
echo $currency['name'], "\n";
echo $currency['code_alpha'], "\n";
echo $currency['code_numeric'], "\n";
echo "+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+\n";
}
?>
Live DEMO.
You can use DomDocument to achieve this objective.
Check on this post http://www.developersnote.com/2013/12/how-to-read-xml-file-in-php.html
$objDOM = new DOMDocument();
//Load xml file into DOMDocument variable
$objDOM->load("../configuration.xml");
//Find Tag element "config" and return the element to variable $node
$node = $objDOM->getElementsByTagName("config");
//looping if tag config have more than one
foreach ($node as $searchNode) {
$dbHost = $searchNode->getAttribute('host');
$dbUser = $searchNode->getAttribute('userdb');
$dbPass = $searchNode->getAttribute('dbpass');
$dbDatabase = $searchNode->getAttribute('database');
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With