Currency Exchange Rate in PHP

We might sometime need to deal with multiple type of currencies when developing e-commerce website. Multiple type of currencies mean we have to take care and get updated currency exchange rate to correctly fix the price of any product. In PHP, we can easily make use of Yahoo Finance to generate currency exchange rate.

<?php

// $from => Currency to convert from
// $to   => Currency to convert to
function get_exchange_rate ($from, $to){
    $currency = [ "from" => $from, "to" => $to ];
    $ticker = $currency["from"] . $currency["to"] . "=X";

    // Retrieve data from Yahoo Finance
    $open = fopen("http://quote.yahoo.com/d/quotes.csv?s=$ticker&f=sl1d1t1c1ohgv&e=.csv", "r");
    $exchange_rate = fread($open, 2000);
    fclose($open);
    $exchange_rate = str_replace("\"", "", $exchange_rate);
    $exchange_rate = explode(",", $exchange_rate);

    // return exchange rate
    return $exchange_rate;
}

$rate_USD_SGD = get_exchange_rate("USD", "SGD");
?>

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s