Get live currency using PHP

Posted on November 8 2009 by zemog

Few years ago I made a script that will get a live currency from a certain site and display the information on my page. After a few hours of looking into my old file, I can not find my script so I made a new one. I remember I use the cURL function but I forgot the website I used to get the data (am I too forgetful these day? hmm)

Without any other choice, I have to use my friend Google for some clues. Throwing different search keys such as “currency converter using PHP”, “live currency feed”, “currency feed”, “pesos to usd conversion using php”, etc., I came across with this forum http://forums.whirlpool.net.au/forum-replies-archive.cfm/783963.html in which the last thread says

Could always use Google.

www.google.com.au/search?q=100+aud+in+usd

Yeah, why not use Google’s own conversion!

So here is the code.


if (function_exists('curl_init'))
{
$ch = curl_init();

curl_setopt($ch, CURLOPT_URL,
'http://www.google.com.au/search?hl=en& q=1+usd+in+php&btnG=Search&
meta=&aq=f&oq=');
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_USERAGENT,
'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.7.5) Gecko/20041107 Firefox/1.0');

$content = curl_exec($ch);

curl_close($ch);

$position1 	= strpos($content,"1 U.S. dollar =");
$cleandata 	= substr($content,$position1+15,7);
echo $cleandata;
}
else
{
echo "sorry no cURL here";
}

Let me discuss to you some points

First there is the condition to check whether cURL is available of not. -> if (function_exists(‘curl_init’))
The most interesting part here is the url

http://www.google.com.au/search?hl=en&q=1+usd+in+php&btnG=Search&meta=&aq=f&oq=

How did I get that url? What I did was put the query “1 usd in php” which translate to 1 US dollar to philippine peso. Then the result appears

1 usd to php

1 usd to php

Now that Google have displayed the result, all we need to do is read the html file using cURL and using some string manipulations you can easily get what you want. In the example above you should get the value 47.499


Share This Post

3 Responses to “Get live currency using PHP”

  1. Really worth my time. I just want to encourage you in continuing to post entries such as this one. Thank you.

  2. Thanks so much for publishing this.

  3. I have a preference for utilizing computerized systems myself, but I can unquestionably accept the points you’re putting out above. You’ve greater experience and more valid insights than most of those who are writing about trading on the internet. Thanks for the useful article.