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.


// $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("$ticker&f=sl1d1t1c1ohgv&e=.csv", "r");
    $exchange_rate = fread($open, 2000);
    $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");



Leave a Reply

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

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

Google photo

You are commenting using your Google 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 )

Connecting to %s