26

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?

5

15 Answers 15

13

After searching a lot, found this.

// Fetching JSON
$req_url = 'https://api.exchangerate-api.com/v4/latest/USD';
$response_json = file_get_contents($req_url);

// Continuing if we got a result
if(false !== $response_json) {

    // Try/catch for json_decode operation
    try {

    // Decoding
    $response_object = json_decode($response_json);

    // YOUR APPLICATION CODE HERE, e.g.
    $base_price = 12; // Your price in USD
    $EUR_price = round(($base_price * $response_object->rates->EUR), 2);

    }
    catch(Exception $e) {
        // Handle JSON parse error...
    }
}

This is working fine. The snippet is from: https://www.exchangerate-api.com/docs/php-currency-api

1
8

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;
1
6

An example of converting EUR to USD

$url = 'http://www.webservicex.net/CurrencyConvertor.asmx/ConversionRate?FromCurrency=EUR&ToCurrency=USD';
            $xml = simpleXML_load_file($url,"SimpleXMLElement",LIBXML_NOCDATA);
            if($xml ===  FALSE)
            {
               //deal with error
            }
            else { 

                $rate = $xml;
            }
2
  • This is definitely cleaner and a more robust solution than the others mentioned here.
    – Doggie52
    Sep 3, 2013 at 7:53
  • 2
    404 Not Found - this service is not longer available.
    – Johncl
    Apr 1, 2018 at 5:37
4

My 2017 solution is a very lightweight function that gets the current exchange informations from the fixer.io API. It also stores the exchange rate in a daily cookie to prevent further heavy web loading time. You can also choose Sessions for that or remove it:

function convertCurrency($amount, $from = 'EUR', $to = 'USD'){
    if (empty($_COOKIE['exchange_rate'])) {
        $Cookie = new Cookie($_COOKIE);
        $curl = file_get_contents_curl('http://api.fixer.io/latest?symbols='.$from.','.$to.'');
        $rate = $curl['rates'][$to];
        $Cookie->exchange_rate = $rate;
    } else {
        $rate = $_COOKIE['exchange_rate'];
    }
    $output = round($amount * $rate);

    return $output;
}

Example usage to convert 100 euro to pounds:

echo convertCurrency(100, 'EUR', 'GBP');

2
  • Website seems to require you to register for an API key.
    – Johncl
    Apr 1, 2018 at 5:38
  • It seems its still possible to call this without a key, although it seems your assumption about its format is wrong. It always uses base currency EUR by default, and what you provide as symbols is what currencies you want rates for towards that base currency. You have to do the math yourself to go between those based on those rates.
    – Johncl
    Apr 1, 2018 at 5:53
3

Use Given code for currency Converter PHP

public function convertCurrency($from, $to, $amount)    
{
    $url = file_get_contents('https://free.currencyconverterapi.com/api/v5/convert?q=' . $from . '_' . $to . '&compact=ultra');
    $json = json_decode($url, true);
    $rate = implode(" ",$json);
    $total = $rate * $amount;
    $rounded = round($total);
    return $total;
}
2

I like the first solution but there seems to be on BIG problem with it. I tried to implement it into a payment gateway but I kept on getting a result of 1. This perplexed me and I eventually found that it is because there is a space used by google for the thousands sparator. Thus the amount of 1 500.00 was returned as one since the rest was exploded. I have created a quick and dirty fix for it. Let me know if anyone else has experienced this problem. Here is my solution:

function currency($from_Currency,$to_Currency,$amount) {
  $amount = urlencode($amount);
  $from_Currency = urlencode($from_Currency);
  $to_Currency = urlencode($to_Currency);
  $url = "http://www.google.com/ig/calculator?hl=en&q=$amount$from_Currency=?$to_Currency";
  $ch = curl_init();
  $timeout = 0;
  curl_setopt ($ch, CURLOPT_URL, $url);
  curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
  curl_setopt($ch,  CURLOPT_USERAGENT , "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1)");
  curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
  $rawdata = curl_exec($ch);
  curl_close($ch);
  $data = explode('"', $rawdata);
  $data = explode('.', $data['3']);
  $data[0] = str_replace(" ", "",preg_replace('/\D/', '',  $data[0]));
  if(isset($data[1])){
    $data[1] = str_replace(" ", "",preg_replace('/\D/', '', $data[1]));
    $var = $data[0].".".$data[1];        
  } else{
    $var = $data[0];
  }
  return round($var,2); }
1
  • 2
    iGoogle was retired on November 1, 2013. This API no longer works.
    – reformed
    Jul 27, 2016 at 14:13
2

This is what I'm using:

function exchangeRate( $amount, $from, $to)
{
    switch ($from) {
        case "euro":
            $from_Currency = "EUR";
            break;
        case "dollar":
            $from_Currency = "USD";
            break;
        case "pounds":
            $from_Currency = "GBP";
            break;
    }

    switch ($to) {
        case "euro":
            $to_Currency = "EUR";
            break;
        case "dollar":
            $to_Currency = "USD";
            break;
        case "pound":
            $to_Currency = "GBP";
            break;
    }

  $amount = urlencode($amount);

  $from_Currency = urlencode($from_Currency);
  $to_Currency = urlencode($to_Currency);
  $get = file_get_contents("https://www.google.com/finance/converter?a=$amount&from=" . $from_Currency . "&to=" . $to_Currency);

  $get = explode("<span class=bld>",$get);
  $get = explode("</span>",$get[1]);
  $converted_amount = preg_replace("/[^0-9\.]/", null, $get[0]);
  return round($converted_amount, 2);
}
2

I used the following PHP to pull data from the ECB as Stefan Gehrig suggested.

<?php
try {
    $xml_string = file_get_contents("https://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml");
    $xml = new SimpleXMLElement($xml_string);
    $cxml = $xml->xpath('//*[@currency]');
    //anchored to USD in this case
    $usx = $xml->xpath('//*[@currency="USD"]');
    $base = floatval(strval($usx[0]['rate']));
    //create a simple associative array with the 3-letter code
    //as the key and the rate as the value
    $c_arr = array();
    foreach ($cxml as $c) {
        $cur = strval($c['currency']);
        $rate = floatval(strval($c['rate']))/$base;
        $c_arr[$cur] = $rate;
    }
    //add the euro since it's assumed as the base rate for the ECB
    $c_arr['EUR'] = 1/$base;
    $currency_json = json_encode($c_arr);

    //write to file
    $file = "currency.json";
    $fh = fopen($file, 'w') or die("can't open file");
    fwrite($fh, $currency_json);
    fclose($fh);
    echo $currency_json;
} catch (Exception $e) { echo $e; }
?>

It writes a JSON file that I include as a JavaScript variable:

<script type="text/javascript">
var data = <?php include('currency.json'); ?>;
</script>

I can then easy grab the data using the 3-letter currency code (e.g., data['GBP']) with JavaScript when a currency change is requested.

I use a Cron Job to update the JSON once a day, so it's not making a call each time the page is visited.

1
/**
 * Rechnet den gegebenen Betrag von einer Währung in eine andere um
 * @param FLOAT $value
 * @param STRING $fromCurrency=USD Ursprungswärung des Betrags
 * @param STRING $toCurrency=EUR Zielwärhung, in die umgerechnet wird
 * @param BOOL $round=true Wenn aktiviert, wird der errechnete Wert auf 2 Nachkommastellen kaufmännisch gerundet
 * @return ARRAY [timestamp][datetime_iso][datetime_de][value][from][to][result]
 */
function calcCurrency($value=0, $fromCurrency='USD', $toCurrency='EUR', $round=true) {
    $timestamp = time();
    $fromCurrency = preg_replace('[^A-Z]', '', strtoupper(trim($fromCurrency)));
    $toCurrency = preg_replace('[^A-Z]', '', strtoupper(trim($toCurrency)));
    $round = (bool) $round;

    $wrongJSON = file_get_contents("http://www.google.com/ig/calculator?hl=en&q=1$fromCurrency=?$toCurrency");
    $search = array('lhs', 'rhs', 'error', 'icc');
    $replace = array('"lhs"', '"rhs"', '"error"', '"icc"');
    $json = str_replace($search, $replace, $wrongJSON);
    $jsonData = json_decode($json, true);
    if ('' !== $jsonData['error']) throw new Exception('FEHLER: '.$jsonData['error']);
    $rhs = explode(' ', $jsonData['rhs'], 2);

    $calcValue = floatval(0.00);
    $value = floatval($value);
    $ratio = floatval($rhs[0]);

    // Gültigkeitsprüfungen
    if ($value < 0) throw new Exception('Umzurechnender Wert darf nicht negativ sein.');

    // Plausibilitätsprüfung der eingestellten Währung und Festlegung
    if ($toCurrency == $fromCurrency) {
        // Ursprungswährung = Zielwährung | Es erfolgt keine Berechnung
        $calcValue = $value;
        $ratio = 1;
    } else {
        $calcValue = floatval($value * $ratio);
    }

    // Array mit Rückgabewerten erzeugen und zurück geben
    return array(
        'timestamp' => $timestamp,
        'datetime_iso' => date('Y-m-d H:i:s', $timestamp),
        'datetime_de' => date('d.m.Y H:i:s', $timestamp),
        'value' => $value,
        'from' => $fromCurrency,
        'to' => $toCurrency,
        'ratio' => round($ratio, 6),
        'result' => (true===$round)
            ? round($calcValue, 2)
            : $calcValue
    );
}
1
  • 2
    iGoogle was retired on November 1, 2013. This API no longer works.
    – reformed
    Jul 27, 2016 at 14:12
1

use this simple function :

function convertCurrency($amount, $from, $to){
    $url  = "https://www.google.com/finance/converter?a=$amount&from=$from&to=$to";
    $data = file_get_contents($url);
    preg_match("/<span class=bld>(.*)<\/span>/",$data, $converted);
    $converted = preg_replace("/[^0-9.]/", "", $converted[1]);
    return round($converted, 3);
}
1
  • In 2017 and above I don't encourage to use this function since it adds up a huge page loading time. Especially if you convert multiple numbers, because this isn't an API, it downloads the whole webpage and just extracts HTML for values you're looking for. Instead take a look at my answer using the fixer.io API.
    – AlexioVay
    Aug 31, 2017 at 20:49
0

This is so simple if you use a local server like wamp or xampp or other server then you should have to enable extension of openssl first in php.ini

extension=php_openssl.dll `allow_url_fopen = On`

then you will be able to run my code else you are runing your website with online hosting then you dont need to do this so you have to add this php function in your php script

<?php
function currencyCnv( $amount, $from, $to){
$get = file_get_contents("https://www.google.com/finance/converter?a=$amount&from=" . $from. "&to=" . $to);
$get = explode("<span class=bld>",$get);
$get = explode("</span>",$get[1]);
$converted_amount = $get[0];
echo round($converted_amount,2);
}

  currencyCnv(100,'GBP','PKR');
//currencyCnv(you amount from form input filed ,currency from select box,currency to select box)
//any currency convert with this code 
0

Please check below currency change example.

    function oneUSDTo($amount, $toCurrency)
{
$currencyUrl = $amount."usd+to+$toCurrency";
$url = "https://www.google.com/search?q=".$currencyUrl;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

$result = curl_exec($ch);
$data = explode("$amount US Dollar = ",$result);
return (float) substr($data[1],0,10);
}

//Usage: oneUSDTo("type currency code here");
echo oneUSDTo("5","EUR");
0
https://fincharts.info/charts/exchange/?key=api_key&&from=USD&to=GBP,BWP,ZAR&amount=45854&date=2018-03-03&base=USD

seems you have to signup for an api key, I think

0

You can also check: https://free.currencyconverterapi.com

Disclaimer, I'm the author of this website.

A sample conversion URL is: http://free.currencyconverterapi.com/api/v6/convert?q=PHP_EUR,EUR_PHP&compact=ultra&apiKey=sample-api-key which will return a value in json format, e.g. {"PHP_EUR":0.016434,"EUR_PHP":60.849184}

You should note about the limitations though like maximum requests and queries (details found the website). I've implemented limits because there have been abusers of the service.

I've started this since 2014 and has been up ever since (aside from the link change and maintenance down times along the way). I personally use it for my other websites, and provided the service publicly so it can help other devs as well.

Anyway hope this helps, and here's a sample PHP code:

<?php
function convertCurrency($amount, $from, $to){
  $conv_id = "{$from}_{$to}";
  $string = file_get_contents("https://free.currencyconverterapi.com/api/v6/convert?q=$conv_id&compact=ultra&apiKey=sample-api-key");
  $json_a = json_decode($string, true);

  return $amount * round($json_a[$conv_id], 4);
}

echo(convertCurrency(5, "USD", "PHP"));
?> 
0
<?php
//  replace this key from  fixer.io after getting  a free API access key:

$API = '314259bbe6de76b961c84a5244ac0fc0';

function convertCurrency($API, $amount, $from = 'EUR', $to = 'USD'){
  $curl = file_get_contents("http://data.fixer.io/api/latest?access_key=$API&symbols=$from,$to");

  if($curl)
  {
    $arr = json_decode($curl,true);
    if($arr['success'])
    {
        $from = $arr['rates'][$from];
        $to = $arr['rates'][$to];

        $rate = $to / $from;
        $result = round($amount * $rate, 6);
        return $result;
    }else{
        echo $arr['error']['info'];
    }
  }else{
    echo "Error reaching api";
  }
}

echo convertCurrency($API, 1, 'USD', 'EGP');
4
  • Fixer is no longer free.
    – Johncl
    Mar 2, 2019 at 16:52
  • no, there is still a free plan for 1.000 API Calls / month
    – Behiry
    Mar 2, 2019 at 18:07
  • {"success":false,"error":{"code":103,"info":"This API Function does not exist."}} Aug 8, 2019 at 13:13
  • @ZainFarooq Please try the updated code after getting a free account at fixer
    – Behiry
    Aug 15, 2019 at 10:36

Not the answer you're looking for? Browse other questions tagged or ask your own question.