This is my personal blog. I also have a professional blog at http://siliconsparrow.com/

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.

4 Comments »

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

    Thanks, that’s what I needed.

  2. Comment by William Irwin — 28 November 2010 @ 3:28 am

    Hi Adam.

    Thank you for this – it’s perfect.

  3. Comment by MarathonStudios — 6 April 2011 @ 11:11 am

    Excellent bit of code!

  4. Comment by sanjay — 20 April 2011 @ 1:42 pm

    thanks

    it’s really helping me

RSS feed for comments on this post.

Leave a comment

COMMENTS ARE DISABLED DUE TO EXCESSIVE SPAM. I'm sorry about this, I really love to read your comments but the amount of time I spend deleting spam is too much.


Powered by WordPress