ADAM'S WEB PRESENCE

22 October 2008

Currency Calculation in PHP

Filed under: General — adam @ 9:03 pm

Thanks to some help from Stack Overflow, the new and excellent Q&A site for programmers, I have put together a PHP class which can perform a currency conversion using up to date exchange rates pulled live from Yahoo. Here is the code for y’all to share:

<?php

// fx.php - PHP Code to convert currencies using Yahoo's currency conversion service.
// by Adam Pierce <adam@doctort.org> 22-Oct-2008
// This code is public domain.

class ForeignExchange
{
	private $fxRate;

	public function __construct($currencyBase, $currencyForeign)
	{
		$url = 'http://download.finance.yahoo.com/d/quotes.csv?s='
			.$currencyBase .$currencyForeign .'=X&f=l1';

		$c = curl_init($url);
		curl_setopt($c, CURLOPT_HEADER, 0);
		curl_setopt($c, CURLOPT_RETURNTRANSFER, 1);
		$this->fxRate = doubleval(curl_exec($c));
		curl_close($c);
	}

	public function toBase($amount)
	{
		if($this->fxRate == 0)
			return 0;

		return  $amount / $this->fxRate;
	}

	public function toForeign($amount)
	{
		if($this->fxRate == 0)
			return 0;

		return $amount * $this->fxRate;
	}
};

?>

Because it creates an object, that object will remember the exchange rate so it doesn’t need to look up the rate again and again if you want to do multiple currency conversions on the same web page.

Usage Example:

<?php

// Create an object to convert Australian Dollars to Euros.
    require 'fx.php';
    $fx = new ForeignExchange('AUD', 'EUR');

// This function formats a value with 2 decimal places.
    function fmtMoney($amount)
    {
        return sprintf('.%.2f', $amount);
    }

    $auPrice = 25.50;

    echo '<p>Your price is AU$'. fmtMoney($auPrice)
        .' which is approximately &euro;'. fmtMoney($fx->toForeign($auPrice)) .'</p>';
?>

…enjoy.

1 Comment »

  1. Comment by Mladjo — 21 February 2009 @ 8:49 pm

    Thanks, that’s what I needed.

RSS feed for comments on this post. TrackBack URI

Leave a comment


Powered by WordPress