问题描述
|
我有一个exrate.xml看起来像这样
<!--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>
任何人都知道如何读取xml并输出数据。
货币|购买|销售
我有用
<?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
)
)
如何循环@attributes显示数据?
foreach ($xml as $value){
foreach ($value->@attributes as $key=>$val){ // I have problem here @attributes
}
}
解决方法
使用SimpleXML,可使用
attributes()
方法访问属性:
foreach ($value->attributes() as $key=>$val){
// do something
}
, 尝试这个:
<?php
$xml = simplexml_load_file( \"Service/Forex_Content.xml\" );
foreach( $xml->Exrate[0]->attributes() as $a => $b ) {
echo $a . \'=\"\' . $b .\"\\\"\\n\";
}
编辑:解决了这种情况。
, 将$value->@attributes
替换为$value->attributes()
。您可能必须进一步走到树上才能到达所需的节点,但是您可以在任何项目上调用attributes()
。
, 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);