Currency Conversion using PHP

Click Upvote picture Click Upvote · Jul 19, 2010 · Viewed 65.3k times · Source

I'm looking for a way to convert any amount from one currency to another on a website. The user would enter something like '100' and select USD as the currency, and then chooses Australian or Canadian dollars as the currency to convert to. When he clicks the 'Convert' button, I'd like to convert that amount automatically, through some API, and show him the amount in the currency he chose to convert to.

Any ideas?

Answer

Max picture Max · Jan 29, 2015

This method is using Yahoo currency API Full tutorial : Currency Converter in PHP, Python, Javascript and jQuery

function currencyConverter($currency_from, $currency_to, $currency_input) {
    $yql_base_url = "http://query.yahooapis.com/v1/public/yql";
    $yql_query = 'select * from yahoo.finance.xchange where pair in ("' . $currency_from . $currency_to . '")';
    $yql_query_url = $yql_base_url . "?q=" . urlencode($yql_query);
    $yql_query_url .= "&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys";
    $yql_session = curl_init($yql_query_url);
    curl_setopt($yql_session, CURLOPT_RETURNTRANSFER, true);
    $yqlexec = curl_exec($yql_session);
    $yql_json =  json_decode($yqlexec, true);
    $currency_output = (float) $currency_input * $yql_json['query']['results']['rate']['Rate'];

    return $currency_output;
}

$currency_input = 2;
//currency codes : http://en.wikipedia.org/wiki/ISO_4217
$currency_from = "USD";
$currency_to = "INR";
$currency = currencyConverter($currency_from, $currency_to, $currency_input);

echo $currency_input . ' ' . $currency_from . ' = ' . $currency . ' ' . $currency_to;