Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php read xml file loop over @attributes?

Tags:

php

i have a exrate.xml look like this

 <!--For reference only. Only one request every 5 minutes!-->
    <ExrateList>
    <DateTime>5/29/2011 8:54:12 PM</DateTime>
    <Exrate CurrencyCode="AUD" CurrencyName="AUST.DOLLAR" Buy="21688.77" Transfer="21819.69" Sell="22201.6"/>    
    <Source>source name </Source>
    </ExrateList>

Anybody know how can I read xml and output the data.

currency | buy | sale

I have use

            <?php
              = simplexml_load_file("Service/Forex_Content.xml");
            echo '<pre>';
            print_r($xml);
            echo '</pre>';

        ?>


SimpleXMLElement Object
(
    [DateTime] => 5/29/2011 8:54:12 PM
    [Exrate] => Array
        (
            [0] => SimpleXMLElement Object
                (
                    [@attributes] => Array
                        (
                            [CurrencyCode] => AUD
                            [CurrencyName] => AUST.DOLLAR
                            [Buy] => 21688.77
                            [Transfer] => 21819.69
                            [Sell] => 22201.6
                        )

                )

How Can I loop @attributes to display the data?

foreach ($xml as $value){
    foreach ($value->@attributes as $key=>$val){ // I have problem here @attributes

        }

}
like image 869
newbie Avatar asked Feb 23 '26 17:02

newbie


2 Answers

With SimpleXML, attributes are accessed using the attributes() method:

foreach ($value->attributes() as $key=>$val){
    // do something
}
like image 157
stevevls Avatar answered Feb 25 '26 06:02

stevevls


Try this:

<?php
$xml = simplexml_load_file( "Service/Forex_Content.xml" );
foreach( $xml->Exrate[0]->attributes() as $a => $b ) {
    echo $a . '="' . $b ."\"\n";
}

EDIT: fixed the case.

like image 38
Femi Avatar answered Feb 25 '26 07:02

Femi



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!