Tutorials, PHP & MySQL

Use Google finance calculator to convert currency with PHP

Convert currency from one country to another easily with Google's finance calculator, using that it's possible to collect the output using PHP.</p>

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

Altaf Hussain wrote an excellent function to collect currencies from Google finance you pass the amount, currency from and currency to be converted to.

This example below compresses the code slightly also wraps the final output inside a number_format function to keep the currency in whole number format.

<?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");
?>

 

David Carr

David Carr

For the past 12 years, I’ve been developing applications for the web using mostly PHP. I do this for a living and love what I do as every day there is something new and exciting to learn.

In my spare time, the web development community is a big part of my life. Whether managing online programming groups and blogs or attending a conference, I find keeping involved helps me stay up to date. This is also my chance to give back to the community that helped me get started, a place I am proud to be apart of.

Besides programming I love spending time with friends and family and can often be found together going out catching the latest movie, staying in playing games on the sofa or planning a trip to someplace I’ve never been before.