大家好,
我的一些朋友问我如何在其网站上显示的汇率由罗马尼亚国家银行提供的利率,所以我决定做一个关于它的小教程的人可能会发现它有用。
首先,我们需要阅读提供饲料。 使用下面的代码,我们将做到这一点:
$szFeed = "http://www.bnro.ro/nbrfxrates.xml"; $arrXML = simplexml_load_file($szFeed);
Next, we will need a variable to hold our exchange rates.
$arrCurrency = array();
Assuming we have no errors so far we will have to parse the result hold in $arrXML.
We will do this with a “foreach” loop:
$nIndex = 0;
foreach($arrXML->Body->Cube->Rate as $rate)
{
// we need a variable to store attributes for rate element
$arrAttribute = array();
// the rate element can have two possible attributes:
// currency and multiplier as exemplified below
// <Rate currency="GBP">4.7690</Rate>
// <Rate currency="HUF" multiplier="100">1.4603</Rate>
//
$arrAttribute = $arrXML->Body->Cube->Rate[$nIndex]->attributes();
//check to see if multiplier is present
if ($arrAttribute[1] != null) $szMultiplier = " x " . $arrAttribute[1];
else $szMultiplier = "";
$arrCurrency["{$arrAttribute[0]}"] = $rate;
// now print the currency
echo "$nIndex - 1 $arrAttribute[0] $szMultiplier = $rate RON" . "<br />";
$nIndex++;
}
If you wish to extract only the rate for EUR you get it from $arrCurrency["EUR"].
Off course you have to add some error checking on the way.
If you want to learn more about simplexml_load_file you can check the official php manual .
Download the source code here: Source code for exchange rates tutorial .
Hope you liked it.
More From Armino's programming and design blog
- Gimp tutorial: How to create an aluminum style background
- Gimp tutorial – How to create a nice dotted background
- Ubuntu 11.10 Oneiric Ocelot it’s on its way – Alpha 2 released














Instead simplexml_load_file I prefer to use curl.
I am not sure does simplexml_load_file use file_get_contents technique, but curl have much better performances then file_get_contents. Please follow curl vs file_get_contents .
It would be nice to do few performance tests.
Of course, caching fetched data is a very important feature . If your site have much visitors, and you do requests to remote server for each visitor, the remote server may “detect attack”.