简体   繁体   中英

php read xml file loop over @attributes?

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

        }

}

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

foreach ($value->attributes() as $key=>$val){
    // do something
}

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.

Replace $value->@attributes with $value->attributes() . You may have to go further down the the tree to get to the node you want, but you can call attributes() on any item.

function recurseXML($xml, $step)
{
    echo "<table cellpadding=\"2\" cellspacing=\"2\" width=\"100%\" border=\"1\">";
    $step++;
    foreach($xml as $key0 => $value)
    {
        if($key0=='Exrate')
        {           
            echo "\n<tr>\n";                   
            foreach($value->attributes() as $attributeskey0 => $attributesvalue1)
            {    
                echo " <td> [$attributeskey0] = $attributesvalue1</td>\n";  
            }
            echo "</tr>\n\n";
        }
        else
        {
           echo "\n<tr><td colspan=\"5\">$value</td></tr>";
        }           
    }
    echo "</table>\n";
}
$xml = simplexml_load_file("http://www.vietcombank.com.vn/ExchangeRates/ExrateXML.aspx");
recurseXML($xml, 0);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM