PHP > Currency Conveter
Every web site that deals with economics needs to be able to handle different currencies. EyeCurrencyConverter to the rescue! Another simple PHP class which will use an up-to-date XML feed to convert between two different currencies. How simple? This simple:
<?php
// Load the curency converter class
$con = new EyeCurrenyConvert();
// Convert $5.78 from United States to Canadian
echo $con->convert('USD', 'CAD', '5.78');
This script uses a XML feed provided by the Danmarks Nationalbank. To get a CODE for the currency you're converting from/to, open the XML document and find the "CODE" attribute for the currency you want to use.
Here is the code for the class:
<?php
class EyeCurrenyConvert
{
public $stream;
const feed = 'http://www.nationalbanken.dk/dndk/valuta.nsf/valuta.xml';
/**
* Constructor
*
* @return boolean
*/
public function __construct()
{
if (!$this->stream = simplexml_load_file(self::feed))
return false;
return true;
}
/**
* Convert between two currencies
*
* @param string $from The "CODE" of the currency you are converting from
* @param string $to The "CODE" of the currency you are converting to
* @param float $amount The amount to convert
* @return mixed Float when successful and false when an error occured
*/
public function convert($from, $to, $amount)
{
if($this->stream)
{
$rate_from = $this->fetchRate($from);
$rate_to = $this->fetchRate($to);
if ($rate_from and $rate_to)
return (float) number_format(($amount * $rate_from) / $rate_to, 2);
}
return false;
}
/**
* Fetch rate from XML
*
* @param string $code The "CODE"
* @return mixed False on error and currency rate when code is found
*/
private function fetchRate($code)
{
if(!$this->stream)
return false;
foreach ($this->stream->dailyrates->currency as $curr)
{
if ($curr['code'] == $code)
return ereg_replace(',', '.', $curr['rate']);
}
return false;
}
}