Use Google finance calculator to convert currency with PHP

David Carr

PHP & MySQL Tutorials

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

 

Fathom Analytics $10 discount on your first invoice using this link

David Carr - Laravel Developer

Hi, I’m David Carr

A Senior Developer at Vivedia
I love to use the TALL stack (Tailwind CSS, Alpine.js, Laravel, and Laravel Livewire)

I enjoy writing tutorials and working on Open Source packages.

I also write books. I'm writing a new book Laravel Testing Cookbook, This book focuses on testing coving both PestPHP and PHPUnit.

Sponsor me on GitHub

Subscribe to my newsletter

Subscribe and get my books and product announcements.

Laravel Testing Cookbook

Help support the blog so that I can continue creating new content!

Fathom Analytics $10 discount on your first invoice using this link

Subscribe to my newsletter

Subscribe and get my books and product announcements.

© 2006 - 2023 DC Blog. All code MIT license. All rights reserved.