2010-03-17 112 views
2

我需要货币换算,欧元兑美元。
欧洲央行提供的利率在这里:
http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml
我可以使用的第一个节点获得的美元汇率,但如果他们改变什么顺序?
我需要更可靠的东西吗?我不知道如何..PHP simpleXML解析

$xml = @simplexml_load_file('http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml'); 
echo "dollar: " . $xml->Cube->Cube->Cube[0]->attributes()->rate; 

回答

6

只需使用XPath获取任何具有@currency属性等于“USD”的节点,就可以实现这一点。

$xref = simplexml_load_file('http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml'); 
$nodes = $xref->xpath('//*[@currency="USD"]'); 

echo $nodes[0]['rate']; 
0

您可以通过迭代的SimpleXML用foreach

foreach($xml->Cube->Cube as $cube) { 
    if(isset($cube->attributes()->rate)) { 
     $rate = $cube->attributes()->rate; 
    }  
} 
0

您可以使用XPath

$rate = $xml->xpath("//Cube[currency='USD']/rate") 
0

你是对的。目前,您假设0th条目为USD,如果订单在将来发生变化,则您的假设失败。因此,为了使您的应用程序独立于订单,您可以在循环中检查currency属性。当您找到值为"USD"的那一刻时,您可以获得其相应的rate属性。