jump to navigation

Building a Currency Converter with Ajax-PHP and Google’s Calculator API August 27, 2012

Posted by Tournas Dimitrios in PHP.
trackback

Well of course , Google is the King  for searching the web for information , but it has also many other web-services . One of the lesser known services is Google-Calculator , not only can it be used to solve simple math problems , but also to convert measurements or currencies . Google calculator isn’t supported officially , so I’m not sure how accurate the currency-conversion is . My intention is just to demonstrate how to combine different open-source technologies to achieve a specific result . For reliable currency information I would use other resources / web-services (at the end of this article , some  links are pointing to RSS-feeds that can be parsed to retrieve accurate currency information ) .

Google’s currency calculator accepts an URL which is url-encoded with a string that contains three values : (amount , from-currency and to-currency) . Then it returns a Json-like string which can be parsed with PHP to extract the converted value .  “Json-like” , means that the string isn’t valid Json , so we can’t use PHP’s native json_decode function , instead , custom code will be used to extract the information  . The query with the acompanion returned calculation has the following format :


http://www.google.com/ig/calculator?hl=en&q=1USD=?EUR
RESULT:
{lhs:"1U.S.dollar",rhs:"0.7993605Euros",error:"",icc:true}

Update 02/10/2012 : The code on this article  emphasizes the basic concepts of the currency converter , for production , a new version is released on GitHub . It has some improvements and a better CSS layout . I would like to thank Patrick Idén for the efforts he made to edit the layout of the script ( CSS ) and for maintaining the demo on his server .   Clone the code from GitHub with your favorite Git-client (if you are not comfortable with Git  , just download this zip-file) .

How the code works :

  1. A user selects currencies (via drop-down boxes) , set the proper amount (in the input-text field) and presses the “convert” button .
  2. JQuery caches the data submitted by the user and creates an url-string . This string is passed to the Ajax-call as a parameter .
  3. Ajax queries “currency-converter.php” and pas the parameters (from step 2) as a POST request .
  4. POST content are extracted , filtered , url-encoded  by “currency-converter.php” .  A request is made to Google’s calculator API . We can use  PHP’s  “curl”  extension or “file_get_contents” function , the code that follows has  examples for both methods  .
  5. Google returns a result  ( Json-like string) , which is parsed by PHP . The returned string also contains a variable-name  “error: ” , which is empty , if for some reason an error was occurred  (we passed an un-recognized currency)  , the “error : ” variable will be set with an error-code .
    Our code detects the “error:” code and returns a proper message to the user .
  6. If everything went correct , the parsed value is returned to the Ajax request (step 3)  . Jquery parses the result and appends it into the HTML-code .

Client-side Code : 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
 <head>
<title>Currency converter with PHP, Ajax and Google calculator API</title>
<link rel="stylesheet" type="text/css" media="screen" href="styles.css" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
    $('#submit').click(function(){
     //Get the values
     var amount = $('#amount').val();
     var from  = $('#from').val();
     var to = $('#to').val();
     var params = "amount=" + amount + "&from=" + from + "&to=" + to ;

     $.ajax({
       type: "POST",
       url: "currency-converter.php",
       data: params ,
       success: function(data){
            $('#converted_value').html(amount + from +" is equal to : " +data);

       }
     });
    }) ;
	});
</script>
</head>
<body>
<div id="page">

    <div class="block rounded">
        <h2>Currency converter with PHP, Ajax and Google calculator API</h2>
    </div>

    <div   class="block_main rounded">

       <?php
$currencies = array(
"USD" => "United States Dollars - USD" ,
"EUR" => "Euro - EUR" ,
"GBP" => "United Kingdom Pounds - GBP" ,
"JPY" => "Japan Yen - JPY" ,
"CNY" => "China Yuan Renminbi - CNY" ,
"CNY" => "RMB (China Yuan Renminbi) - CNY" ,
"RUB" => "Russia Rubles - RUB" ,
"CAD" => "Canada Dollars - CAD" ,
"AUD" => "Australia Dollars - AUD" ,
"ARS" => "Argentina Pesos - ARS" ,
"BHD" => "Bahrain Dinars - BHD" ,
"BRL" => "Brazil Reais - BRL" ,
"BGN" => "Bulgaria Leva - BGN" ,
"CHF" => "Switzerland Francs - CHF" ,
"ZAR" => "South Africa Rand - ZAR" ,
"DZD" => "Algeria Dinars - DZD" ,
"NZD" => "New Zealand Dollars - NZD" ,
"INR" => "India Rupees - INR" ,
"CLP" => "Chile Pesos - CLP" ,
"COP" => "Colombia Pesos - COP" ,
"CRC" => "Costa Rica Colones - CRC" ,
"HRK" => "Croatia Kuna - HRK" ,
"CZK" => "Czech Republic Koruny - CZK" ,
"DKK" => "Denmark Kroner - DKK" ,
"DOP" => "Dominican Republic Pesos - DOP" ,
"EGP" => "Egypt Pounds - EGP" ,
"EEK" => "Estonia Krooni - EEK" ,
"FJD" => "Fiji Dollars - FJD" ,
"HKD" => "Hong Kong Dollars - HKD" ,
"HUF" => "Hungary Forint - HUF" ,
"ISK" => "Iceland Kronur - ISK" ,
"INR" => "India Rupees - INR" ,
"IDR" => "Indonesia Rupiahs - IDR" ,
"ILS" => "Israel New Shekels - ILS" ,
"IQD" => "Iraqi Dinar - IQD" ,
"JMD" => "Jamaica Dollars - JMD" ,
"JOD" => "Jordan Dinars - JOD" ,
"KES" => "Kenya Shillings - KES" ,
"KRW" => "Korea (South) Won - KRW" ,
"KWD" => "Kuwait Dinars - KWD" ,
"LBP" => "Lebanon Pounds - LBP" ,
"MYR" => "Malaysia Ringgits - MYR" ,
"MUR" => "Mauritius Rupees - MUR" ,
"MXN" => "Mexico Pesos - MXN" ,
"MAD" => "Morocco Dirhams - MAD" ,
"NZD" => "New Zealand Dollars - NZD" ,
"NOK" => "Norway Kroner - NOK" ,
"OMR" => "Oman Rials - OMR" ,
"PKR" => "Pakistan Rupees - PKR" ,
 "PEN" => "Peru Nuevos Soles - PEN" ,
 "PHP" => "Philippines Pesos - PHP" ,
 "PLN" => "Poland Zlotych - PLN" ,
 "QAR" => "Qatar Riyals - QAR" ,
 "RON" => "Romania New Lei - RON" ,
 "RUB" => "Russia Rubles - RUB" ,
 "SAR" => "Saudi Arabia Riyals - SAR" ,
 "SGD" => "Singapore Dollars - SGD" ,
 "SKK" => "Slovakia Koruny - SKK" ,
 "ZAR" => "South Africa Rand - ZAR" ,
 "KRW" => "South Korea Won - KRW" ,
 "LKR" => "Sri Lanka Rupees - LKR" ,
 "SEK" => "Sweden Kronor - SEK" ,
 "CHF" => "Switzerland Francs - CHF" ,
 "TWD" => "Taiwan New Dollars - TWD" ,
 "THB" => "Thailand Baht - THB" ,
 "TTD" => "Trinidad and Tobago Dollars - TTD" ,
 "TND" => "Tunisia Dinars - TND" ,
 "TRY" => "Turkey Lira - TRY" ,
 "AED" => "United Arab Emirates Dirhams - AED" ,
 "VEB" => "Venezuela Bolivares - VEB" ,
 "VND" => "Vietnam Dong - VND" ,
 "ZMK" => "Zambia Kwacha - ZMK"
 ) ;

?>
<label for="amount">Amount:</label>
        <input class="amount" type="text" name="amount" id="amount" value="1" />
		<label for="from">From:</label>
        <select name="from" id="from">
<?php
        foreach ($currencies as $k => $v) {
		echo "<option value=\"$k\">$v</option>" ;
        }
?>
        </select>
        <label for="to">To:</label>
        <select name="to" id="to">
 <?php
        foreach ($currencies as $k => $v) {
		echo "<option value=\"$k\">$v</option>" ;
        }
?>
        </select>
        <input type="button" name="submit" id="submit" value="Convert" />
         <div id="converted_value"></div>

    </div>

<div class="footer block_footer rounded">
      <a href="">Back to article</a>
    </div>
</div>
</body>
</html>

Server-side code :

<?php
// Denny  direct-access to this script
 if(!isset($_POST['amount'])){
    header('HTTP/1.0 401 Unauthorized');
    die("Denny access") ;
 }

    $amount = filter_input(INPUT_POST, 'amount', FILTER_VALIDATE_INT) ;
	  if (!is_int($amount) OR $amount <1 ) {
	  echo "Wrong input ..... only numbers greater than zero are accepted" ;
	  exit() ;
	  }
    $amount = substr($amount , 0 ,10)  ;
	// sanitizing input using built in filter_input available from PHP 5.2
    $from   = filter_input(INPUT_POST, 'from', FILTER_SANITIZE_SPECIAL_CHARS) ;
    $to     = filter_input(INPUT_POST, 'to', FILTER_SANITIZE_SPECIAL_CHARS) ;
    // building a parameter string for the query
    $encoded_string = urlencode($amount) . urlencode($from) . '=?' . urlencode($to) ;
    $url = 'http://www.google.com/ig/calculator?hl=en&q=' . $encoded_string ;

/** Use the CURL extension **/
echo currency_converter_curl($url) ;

/** Use the file_get_content  function **/
echo currency_converter_fgc($url) ;

function currency_converter_fgc($url){
$rawdata = file_get_contents($url) ;
return parse_results($rawdata) ;
}

function currency_converter_curl($url ) {
$ch = curl_init();
$timeout = 0;
curl_setopt ($ch , CURLOPT_URL, $url);
curl_setopt ($ch , CURLOPT_RETURNTRANSFER, 1) ;
//Optionaly emulate a browser
//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) ;
return parse_results($rawdata) ;
}

function parse_results($rawdata) {
$data = explode(',' ,  $rawdata) ;
$error = explode('"' , $data['2'] ) ;
if($error[1] > 0) {
return "An error was occured , probably unknown currency " ;
}
$data = explode('"' , $data[1]) ;
//remove the non breaking character that Google API returns with large numbers
return str_replace("\xA0", " ", $data[1]  ) . "<br> "  ;
}

Links for accurate currency Feeds : 

Advertisements

Comments»

1. låna - August 31, 2012

I’ll immediately take hold of your rss as I can’t find your e-mail subscription link or e-newsletter service. Do you have any? Kindly permit me understand in order that I may subscribe. Thanks.

tournasdimitrios1 - August 31, 2012

@låna
Most likely at the bottom-right corner of your browser you will have a “follow” slide-out box . Subscription is only a few clicks (after entering your email-address , one more step is required , verifying it ) . Alternatively , if you have a twitter account , subscribe to my twitter follower-list .
Welcome and thanks for your comment .

2. Intensivo - August 31, 2012

Wow that was odd. I just wrote an incredibly long comment but after I clicked submit my comment
didn’t show up. Grrrr… well I’m not writing
all that over again. Anyways, just wanted to say wonderful blog!

tournasdimitrios1 - August 31, 2012

@Intensivo
Sorry for the inconvenience , due to huge amount of spam messages , I had to enable spam-filters .

3. nice discussion forum - September 2, 2012

Hello there, simply turned into alert to your weblog through Google, and located that it is really informative. I’m going to be careful for brussels. I’ll appreciate if you proceed this in future. Lots of other folks will be benefited from your writing. Cheers!

4. Zack - September 3, 2012

Pretty! This has been a really wonderful article. Thank you for providing this information.

5. Faul - September 5, 2012

A person essentially help to make seriously posts I might state. This is the very first time I frequented your website page and up to now? I amazed with the research you made to create this particular put up incredible. Fantastic process!

6. Mult - September 5, 2012

Hello There. I discovered your weblog the usage of msn. That is a really smartly written article. I will make sure to bookmark it and come back to learn extra of your helpful info. Thank you for the post. I will definitely return.

7. lina - September 10, 2012

Nice post. I used to be checking constantly this weblog and I’m inspired! Extremely helpful info specially the ultimate part 🙂 I maintain such info a lot. I was looking for this particular information for a long time. Thank you and good luck.

8. pypal - September 11, 2012

Somebody essentially help to make seriously articles I would state. That is the very first time I frequented your website page and up to now? I amazed with the analysis you made to make this particular put up extraordinary. Magnificent activity!

9. Mayra - September 13, 2012

Sometimes I contemplate if folks truly take time to publish something original, or are they only just dishing out words to fill a site. This surely doesn’t fit that mold. Thank you for taking the time to write with awareness. Now And Then I look at a page and question whether they even proofread it.Fantastic work with this article.

10. Maxine - September 23, 2012

Greetings! Very helpful advice within this article! It’s the little changes that make the biggest changes. Many thanks for sharing!

11. Donn - September 24, 2012

I’m extremely pleased to uncover this great site. I wanted to thank you for ones time due to this fantastic read!! I definitely enjoyed every bit of it and I have you bookmarked to see new stuff in your web site.

12. love this - September 24, 2012

Not what I was expecting but great anyway! Good for you!

13. Mike - September 24, 2012

My brother recommended I may like this blog. He was entirely right. This post actually made my day. You can not consider just how so much time I had spent for this information! Thanks!

14. Maxine Janke - September 25, 2012

This site was… how do I say it? Relevant!! Finally I’ve found something which helped me. Many thanks!

15. Visitor - October 4, 2012

This is very attention-grabbing, You’re an excessively skilled blogger. I have joined your rss feed and sit up for in the hunt for more of your wonderful post. Also, I have shared your site in my social networks

16. lena - October 8, 2012

I don’t even know how I stopped up right here, but I thought this put up used to be great. I don’t realize who you might be but certainly you’re going to a famous blogger for those who are not already. Cheers!

17. David - October 9, 2012

I just want to tell you that I’m new to weblog and really liked your web-site. Very likely I’m planning to bookmark your blog . You really have terrific articles. Thanks a bunch for sharing with us your website page.

18. Kerl - November 1, 2012

Never knew this, regards for letting me know.

19. Tera - January 10, 2013

Thanks for any other fantastic post. Where else may just anyone get that kind of information in such an ideal method of writing?
I’ve a presentation subsequent week, and I’m at the look for such info.


Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s