Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Use Google finance calculator to convert currency with php
<?php
function convertCurrency($amount, $from, $to){
$data = file_get_contents("https://www.google.com/finance/converter?a=$amount&from=$from&to=$to");
preg_match("/<span class=bld>(.*)<\/span>/",$data, $converted);
$converted = preg_replace("/[^0-9.]/", "", $converted[1]);
return number_format(round($converted, 3),2);
}
echo convertCurrency("10.00", "GBP", "USD");
@ghost

This comment has been minimized.

Copy link

ghost commented Feb 29, 2016

Undefined offset: 1 in $converted = preg_replace("/[^0-9.]/", "", $converted[1]);

@ramielian

This comment has been minimized.

Copy link

ramielian commented May 27, 2017

You saved my project bro thank you so muchhhhhhhhhhh!!!

@msh-shazzad

This comment has been minimized.

Copy link

msh-shazzad commented Jul 2, 2017

Really helped a lot!

@nhantam

This comment has been minimized.

Copy link

nhantam commented Jul 17, 2017

Thank you very much
I have just convert VND to USD. I don't know why google warning: "Could not convert"
https://www.google.com/finance/converter?a=100000&from=VND&to=USD&meta=ei%3DtxtsWbDyKNaruAT7tqr4Dw
Could you help me ?

@cizoDev

This comment has been minimized.

Copy link

cizoDev commented Sep 16, 2017

This API is deprecated.

@anaggh

This comment has been minimized.

Copy link

anaggh commented Sep 17, 2017

@pastoolio

This comment has been minimized.

Copy link

pastoolio commented Sep 20, 2017

Thanks a mil dude, I can confirm changing the URL to https://finance.google.com/finance/converter fixes the issue ;)

@safeith

This comment has been minimized.

Copy link

safeith commented Nov 3, 2017

Thanks, Change URL to " https://finance.google.com/finance/converter" fixed my code too

@moiroca

This comment has been minimized.

Copy link

moiroca commented Nov 8, 2017

Thanks For this man!

@joemar-tagpuno

This comment has been minimized.

Copy link

joemar-tagpuno commented Dec 9, 2017

This is perfect. Thank you for sharing!

@eversionsystems

This comment has been minimized.

Copy link

eversionsystems commented Dec 22, 2017

Great stuff, make sure you use the https://finance.google.com/finance/converter URL. The included one in the code no longer works.

@roy-fdc

This comment has been minimized.

Copy link

roy-fdc commented Dec 27, 2017

Great man, thank you so much bro

@ruchita2212

This comment has been minimized.

Copy link

ruchita2212 commented Jan 24, 2018

Fix mine issue too. Thanks.

@simplesunny

This comment has been minimized.

Copy link

simplesunny commented Mar 19, 2018

but the below link also giving error from last 2 days that 302 moved
https://finance.google.com/finance/converter

@ridham-dholakia92

This comment has been minimized.

Copy link

ridham-dholakia92 commented Mar 19, 2018

https://finance.google.com/finance/converter?a=1&from=$from&to=$to

This is also not working Please Give me some solution for currency conversion api.

@lincetto

This comment has been minimized.

Copy link

lincetto commented Mar 19, 2018

@pastoolio

This comment has been minimized.

Copy link

pastoolio commented Mar 20, 2018

Hey guys.

So I decided to simply write my own function that does the conversion using a standard Google search.

I know it isn't very clean but it works for me. Here is a link to function:

https://pastebin.com/EZJjCEkY

In my example, on the line with the preg_match() function I search for the string 'South African Rand' (The currency of my country) so you will need to adjust this accordingly for your own currency.

I made it this way since I will always convert to South African Rand.

I hope this helps someone.

@shirtmogul

This comment has been minimized.

Copy link

shirtmogul commented Mar 20, 2018

facing the same issue. google has shut down that link.
can xe be used?
http://www.xe.com/currencyconverter/convert/?Amount=10&From=USD&To=INR

what would be the span class? span class=uccResultAmount doesn't seem to work,
what am i doing wrong?

@shoaibshamshere

This comment has been minimized.

Copy link

shoaibshamshere commented Mar 21, 2018

You may convert 1 usd to any currency by this function:

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

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

}

//Usage: oneUSDTo("type currency code here");
echo oneUSDTo("pkr");

@rahulmanayath

This comment has been minimized.

Copy link

rahulmanayath commented Mar 22, 2018

https://finance.google.com/finance/converter

Not working from 2018-03-19 .. Is there any cahnges in API

@newbieAngular4

This comment has been minimized.

Copy link

newbieAngular4 commented Mar 24, 2018

@rahulmanayath have you find any solution for it? Im also looking for solution but no luck :(

@cameraki

This comment has been minimized.

Copy link

cameraki commented Mar 26, 2018

This went down for me as well.

Have a new version from 26th March 2018.

function currencyConverter ($from_Currency, $to_Currency) {
    $from_Currency = urlencode(strtoupper($from_Currency));
    $to_Currency = urlencode(strtoupper($to_Currency));
    $url = file_get_contents('http://free.currencyconverterapi.com/api/v3/convert?q=' . $from_Currency . '_' . $to_Currency . '&compact=ultra');
    $json = json_decode($url, true);

    return $json[$from_Currency . '_' . $to_Currency];
}

More info: https://free.currencyconverterapi.com/

Rate Limits of the Free API
Conversion Pairs per Request: 2
Number of Requests per Hour: 100
Date Range in History: 8 Days
Allowed Back in History: 1 Year(s)
Currency values are updated every 30 minutes

@Timmeh74

This comment has been minimized.

Copy link

Timmeh74 commented Mar 26, 2018

Thanks a lot for the alternative solution @cameraki !

@shirtmogul

This comment has been minimized.

Copy link

shirtmogul commented Mar 27, 2018

@cameraki thanks for this. Is there a $amount variable that can be applied?

@shirtmogul

This comment has been minimized.

Copy link

shirtmogul commented Mar 29, 2018

Okay, this works for me. Hope it helps:

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); //optional, rounds to a whole number
return $total //or return $rounded if you kept the rounding bit from above
}
@activeb

This comment has been minimized.

Copy link

activeb commented Mar 30, 2018

thank you all, it really helped me

@Treeofl1

This comment has been minimized.

Copy link

Treeofl1 commented Apr 2, 2018

Just change your currency as necessary:

<?php
        $from = "ZAR";
        $to = "USD";
        // create curl resource 
        $ch = curl_init(); 

        // set url 
        curl_setopt($ch, CURLOPT_URL, "https://free.currencyconverterapi.com/api/v5/convert?q={$from}_{$to}&compact=ultra"); 

        //return the transfer as a string 
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 

        // $output contains the output string 
        $output = curl_exec($ch);
        // close curl resource to free up system resources 
        curl_close($ch); 
		$data = explode(':', $output);
		$data = explode(" ", $data[1]);
		$amnt = round($data[0], 8);
		echo $amnt;
?>
@mokoshalb

This comment has been minimized.

Copy link

mokoshalb commented Apr 6, 2018

Thanks guys for keeping this gist active :)

@vinefruit

This comment has been minimized.

Copy link

vinefruit commented Apr 9, 2018

Thanks guys for the solutions.

@salsadeanguila

This comment has been minimized.

Copy link

salsadeanguila commented May 11, 2018

Thank you for keeping this alive!

@KhunHtetzNaing

This comment has been minimized.

Copy link

KhunHtetzNaing commented May 26, 2018

i created conversion using a standard Google search.
I know it isn't very clean but it works for me. Here is a link to function:
https://github.com/KhunHtetzNaing/google-currency-converter-api

@hiteshcla00

This comment has been minimized.

Copy link

hiteshcla00 commented Jun 5, 2018

how to replace it

	$get = file_get_contents("https://finance.google.com/bctzjpnsun/converter?a=$encode_amount&from=$from_Currency&to=$to_Currency");
@G10DRAS

This comment has been minimized.

Copy link

G10DRAS commented Jun 8, 2018

This works for me

    import urllib2
    import json
    curr_from = "JPY"
    curr_to = "INR"
    curr_input = 1
    curr_pair = curr_from + "_" + curr_to
    api_url = "https://free.currencyconverterapi.com/api/v5/convert?q={0}&compact=ultra".format(curr_pair)
    jsonurl = urllib2.urlopen(api_url)
    rate_json = json.loads(jsonurl.read())
    rate = curr_input * float(rate_json[curr_pair])
    print rate
@mrshafaq

This comment has been minimized.

Copy link

mrshafaq commented Jun 23, 2018

As google shut down converter link you just need to replace url given below

Just replace:
https://www.google.com/finance/converter?a=
https://finance.google.com/finance/converter?a=
https://finance.google.com/bctzjpnsun/converter?a=
http://free.currencyconverterapi.com/api/v3/convert?q=

with this URL:
https://www.xe.com/currencyconverter/convert/?Amount=

@tresero

This comment has been minimized.

Copy link

tresero commented Jul 10, 2018

@mannyvergel

This comment has been minimized.

Copy link

mannyvergel commented Jul 10, 2018

Thanks for referencing free.currencyconverterapi.com , please use the "v5" onwards API. And just to give a quick update, refresh values are now updated every 60 minutes.

@webmasterashishgaur

This comment has been minimized.

Copy link

webmasterashishgaur commented Jul 22, 2018

Friends don't worry i made the converter working again use the following code
`<?php
function convertCurrency($amount, $from, $to){
$data = file_get_contents("https://www.xe.com/currencyconverter/convert/?Amount=$amount&From=$from&To=$to");
//var_dump($data);
$doc = new DOMDocument;
$doc->loadHTML($data);

$xpath = new DOMXPath($doc);
$node  = $xpath->query("//span[@class='uccResultAmount']")->item(0);
echo trim($node->nodeValue); //=> "$249.95"

}
echo convertCurrency("1", "INR", "USD");`

@graphgear1000

This comment has been minimized.

Copy link

graphgear1000 commented Aug 28, 2018

This is the code my application uses for the google currency api; what would be the code I should use for the free currency converter api? Nothing I've tried works.

function convert($from,$to,$amount) {

    $url = "https://finance.google.com/bctzjpnsun/converter?a=1&from=" . $from . "&to=" . $to;
    $page = file_get_contents($url);
    preg_match_all("/bld>(.*) .*/", $page, $matches);

    $value = $matches[1][0];

    $response = (float) $value * $amount;

    return $response;

}

@alissonlinneker

This comment has been minimized.

Copy link

alissonlinneker commented Aug 29, 2018

@graphgear1000

Fixed:

function convert($from,$to,$amount){
    $url = "https://www.google.com/search?q=".$from.$to;
    $request = curl_init();
    $timeOut = 0;
    curl_setopt ($request, CURLOPT_URL, $url);
    curl_setopt ($request, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt ($request, CURLOPT_USERAGENT,"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36");
    curl_setopt ($request, CURLOPT_CONNECTTIMEOUT, $timeOut);
    $response = curl_exec($request);
    curl_close($request);

    preg_match('~<span [^>]* id="knowledge-currency__tgt-amount"[^>]*>(.*?)</span>~si', $response, $finalData);
    return floatval((floatval(preg_replace("/[^-0-9\.]/","", $finalData[1]))/100) * $amount);
}
@graphgear1000

This comment has been minimized.

Copy link

graphgear1000 commented Aug 29, 2018

Thank you, Alisson, this works like a charm. The only thing was I had to delete "/100" in the last line.

@RRajnishR

This comment has been minimized.

Copy link

RRajnishR commented Oct 3, 2018

@graphgear1000

Fixed:

function convert($from,$to,$amount){
    $url = "https://www.google.com/search?q=".$from.$to;
    $request = curl_init();
    $timeOut = 0;
    curl_setopt ($request, CURLOPT_URL, $url);
    curl_setopt ($request, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt ($request, CURLOPT_USERAGENT,"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36");
    curl_setopt ($request, CURLOPT_CONNECTTIMEOUT, $timeOut);
    $response = curl_exec($request);
    curl_close($request);

    preg_match('~<span [^>]* id="knowledge-currency__tgt-amount"[^>]*>(.*?)</span>~si', $response, $finalData);
    return floatval((floatval(preg_replace("/[^-0-9\.]/","", $finalData[1]))/100) * $amount);
}

Thanks a lot @alissonlinneker.
Though I'd suggest replacing $url with:
$url = "https://www.google.com/search?q=".$from."+to+".$to;
because in some cases like BRL to CAD, Above function was throwing exception.

@RRajnishR

This comment has been minimized.

Copy link

RRajnishR commented Oct 5, 2018

@graphgear1000

Fixed:

function convert($from,$to,$amount){
    $url = "https://www.google.com/search?q=".$from.$to;
    $request = curl_init();
    $timeOut = 0;
    curl_setopt ($request, CURLOPT_URL, $url);
    curl_setopt ($request, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt ($request, CURLOPT_USERAGENT,"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36");
    curl_setopt ($request, CURLOPT_CONNECTTIMEOUT, $timeOut);
    $response = curl_exec($request);
    curl_close($request);

    preg_match('~<span [^>]* id="knowledge-currency__tgt-amount"[^>]*>(.*?)</span>~si', $response, $finalData);
    return floatval((floatval(preg_replace("/[^-0-9\.]/","", $finalData[1]))/100) * $amount);
}

Need a little help here,
I used above code, tested it on my local environment and it worked smooth as butter, but once I uploaded this to my production environment, it started throwing errors, I debugged and found that Google isn't allowing this code to scrape their data. It gives "302 Moved" Error. Further explanation from Google is: "Our systems have detected unusual traffic from your computer network. Please try your request again later". So, anybody has any tip for that??

@deeprajsinha

This comment has been minimized.

Copy link

deeprajsinha commented Oct 24, 2018

Get currency conversion .... https://pastebin.com/TFewge8t

@deeprajsinha

This comment has been minimized.

Copy link

deeprajsinha commented Oct 24, 2018

go for it ...

public function convertCurrency()
{
$amounts = 597;
$from_currency='USD';
$to_currency='INR';
$url = 'https://www.google.co.za/search?q='.$amounts.'+' . $from_currency . '+to+' . $to_currency;

    $cSession = curl_init();

    curl_setopt($cSession, CURLOPT_URL, $url);
    curl_setopt($cSession, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($cSession, CURLOPT_SSL_VERIFYPEER, true);

    $buffer = curl_exec($cSession);
    curl_close($cSession);

    preg_match("/<div class=\"J7UKTe\">(.*)<\/div>/",$buffer, $matches);
    $matches = preg_replace("/[^0-9.]/", "", $matches[1]);
    $amount =  round($matches, 2);
    $total = substr($amount, mb_strlen($amounts));
    return number_format($total,2);
}
@ghost

This comment has been minimized.

Copy link

ghost commented Oct 25, 2018

Hi there, there is free european exchange rates available daily
https://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml

@AyaAhmedEliwa

This comment has been minimized.

Copy link

AyaAhmedEliwa commented Feb 23, 2019

Change URL to " https://finance.google.com/finance/converter" fixed my code

@Devon002

This comment has been minimized.

Copy link

Devon002 commented May 22, 2019

@graphgear1000

Fixed:

function convert($from,$to,$amount){
    $url = "https://www.google.com/search?q=".$from.$to;
    $request = curl_init();
    $timeOut = 0;
    curl_setopt ($request, CURLOPT_URL, $url);
    curl_setopt ($request, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt ($request, CURLOPT_USERAGENT,"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36");
    curl_setopt ($request, CURLOPT_CONNECTTIMEOUT, $timeOut);
    $response = curl_exec($request);
    curl_close($request);

    preg_match('~<span [^>]* id="knowledge-currency__tgt-amount"[^>]*>(.*?)</span>~si', $response, $finalData);
    return floatval((floatval(preg_replace("/[^-0-9\.]/","", $finalData[1]))/100) * $amount);
}

Thank you, Alisson!!!!! ♥

@gautamdrc

This comment has been minimized.

Copy link

gautamdrc commented Jun 8, 2019

Hello
In above all solutions USD to CNY converter not working

Can you please help me

Thanks!!

@snznaota

This comment has been minimized.

Copy link

snznaota commented Jun 26, 2019

Hello
In above all solutions USD to CNY converter not working

Can you please help me

Thanks!!

Yes! Сan you give another solution?

@horlard

This comment has been minimized.

Copy link

horlard commented Aug 8, 2019

can anyone pls help me with any free currency converter api?

@Govindarajn

This comment has been minimized.

Copy link

Govindarajn commented Oct 22, 2019

Any solutions!!

@Navidiscounter

This comment has been minimized.

Copy link

Navidiscounter commented Nov 15, 2019

It is not the best solution and not very clean, but you can do this:

  1. Convert from your old currency to BTC (Bitcoin)
  2. Convert your Bitcoin to your new currency! ;-)

Example for 100 EUR to USD:

  1. 100 EUR to Bitcoin. Result: 0.01282849
    https://blockchain.info/tobtc?currency=EUR&value=100

  2. Convert 01282849 (without "0.") to USD
    https://blockchain.info/frombtc?value=01282849&currency=USD

Attention: In this solution you can convert max 1 full Bitcoin (~8000 EUR)
PHP Code:

function convert($amount, $from, $to)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://blockchain.info/tobtc?currency=" . $from . "&value=" . $amount);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$conversion = curl_exec($ch);
$conversion = substr($conversion, 2);
curl_setopt($ch, CURLOPT_URL, "https://blockchain.info/frombtc?currency=" . $to . "&value=" . $conversion);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
return $conversion = curl_exec($ch);
}
echo convert(100, "EUR", "USD");

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.