A PHP function to convert currencies in real time

0 replies
This PHP function returns the conversion rate of 2 currencies in real time:

PHP Code:
function get_conversion_rate($currency1$currency2) {
$fp = @fsockopen("download.finance.yahoo.com"80$errno$errstr30);
if (!
$fp) { return 1; }
else {
$file "/d/quotes.csv";
$str "?s=".$currency1.$currency2."=X&f=sl1d1t1ba&e=.csv";
$out "GET ".$file.$str." HTTP/1.0\r\n";
$out .= "Host: yahoo.com\r\n";
$out .= "Connection: Close\r\n\r\n";
@
fputs($fp$out);
while (!@
feof($fp)) { $data .= @fgets($fp128); }
@
fclose($fp);
@
preg_match("/^(.*?)\r?\n\r?\n(.*)/s"$data$match);
$data $match[2];
$search = array("'<script[^>]*?>.*?</script>'si""'<[\/\!]*?[^<>]*?>'si""'([\r\n])[\s]+'""'&(quot|#34);'i""'&(amp|#38);'i""'&(lt|#60);'i""'&(gt|#62);'i""'&(nbsp|#160);'i""'&(iexcl|#161);'i""'&(cent|#162);'i""'&(pound|#163);'i""'&(copy|#169);'i""'&#(\d+);'e");
$replace = array("""""\\1""\"""&""<"">"" "chr(161), chr(162), chr(163), chr(169), "chr(\\1)");
$data = @preg_replace($search$replace$data);
$result split(","$data);
return 
$result[1]; } } 
Example:

EUR/USD = get_conversion_rate('EUR', 'USD');

And this function converts an amount in US dollars to an amount in euros
(also in real time):

PHP Code:
function USD_to_EUR($amount) {
if (!
defined('USD_EUR')) { define('USD_EUR'get_conversion_rate('USD''EUR')); }
$amount round(100*USD_EUR*$amount)/100;
return 
$amount; } 
#convert #currencies #function #php #real #time

Trending Topics