Currency Calculation in PHP
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 €'. fmtMoney($fx->toForeign($auPrice)) .'</p>'; ?>…enjoy. Note:
Open JSON API
Good news is here - Google have a secrete API
for Currency Conversion. Its a simple open API you can use for all type of
foreign currencies.
How to use it?
If you want currency converter £ to dollars, use it like
this -
If you want to calculate
currency converter $ to £ -
You can change value of
input currency, for example you want to know the value for $100 in India Rupees
|
Sunday, 14 April 2013
Show Multiple Currency in Shopping Cart
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment