| Len Whistler |
09-10-2012 12:56 AM |
Real Time PHP Currency Converter Function
Real Time PHP Currency Converter Function
I have updated the PHP real time currency converter using quotes from Yahoo Finance which I original posted on March 2007.
http://www.codingforums.com/showthread.php?t=110434
The code below is fully functional and sample output is listed at the bottom. One feature that could be added is to write the exchange rate to a txt file for backup in case the function doesn't connect to Yahoo Finance which happens on rare occasions - this causes an error in the output.
PHP Code:
<?php // ######################################################################### // September 09, 2012 // Real time PHP currency converter function with quotes from Yahoo Finance // Written by Leonard Whistler // lwhistler@gmail.com // #########################################################################
function currencyExchange($amount,$baseCurrency,$quoteCurrency) { $open = fopen("http://quote.yahoo.com/d/quotes.csv?s=$baseCurrency[0]$quoteCurrency[0]=X&f=sl1d1t1c1ohgv&e=.csv", "r"); $exchangeRate = fread($open, 2000); fclose($open); $exchangeRate = str_replace("\"", "", $exchangeRate); $exchangeRate = explode(",", $exchangeRate); $results = ($exchangeRate[1]*$amount); $results = number_format ($results, 2); $amount = number_format ($amount); $timeStamp = strtotime($exchangeRate[2]); $timeStamp = date('F d, Y', $timeStamp); $timeStamp = "$timeStamp $exchangeRate[3]";
echo "$timeStamp EST<br>"; echo "The $baseCurrency[0]/$quoteCurrency[0] exchange rate is $exchangeRate[1]<br>\n"; echo "$amount $baseCurrency[1] will buy $results $quoteCurrency[1]<br><br>\n"; }
// for additional currency ticker symbols visit: http://finance.yahoo.com/currency-converter $usd = array('USD','US Dollars'); $eur = array('EUR','Euro'); $jpy = array('JPY','Japanese Yen'); $gbp = array('GBP','British Pounds'); $aud = array('AUD','Australian Dollars'); $chf = array('CHF','Swiss Francs'); $cad = array('CAD','Canadian Dollars');
// amount, base currency, quote currency. currencyExchange("120",$usd,$eur); currencyExchange("250",$cad,$gbp); currencyExchange("440",$usd,$jpy); currencyExchange("40000",$jpy,$gbp); ?>
Sample output
Code:
September 09, 2012 7:55pm EST
The USD/EUR exchange rate is 0.7816
120 US Dollars will buy 93.79 Euro
September 09, 2012 7:55pm EST
The CAD/GBP exchange rate is 0.6385
250 Canadian Dollars will buy 159.63 British Pounds
September 09, 2012 7:55pm EST
The USD/JPY exchange rate is 78.26
440 US Dollars will buy 34,434.40 Japanese Yen
September 09, 2012 7:55pm EST
The JPY/GBP exchange rate is 0.008
40,000 Japanese Yen will buy 320.00 British Pounds
|