Search code examples
phpgoogle-finance

Google Finance Currency Converter


I am working on google currency converter and it's working fine for all currencies but not showing results of ZAR - BTC conversion.

Google currency converter code :

<?php
function convertCurrency($amount, $from, $to){
    $data = file_get_contents("https://finance.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("1000000", "ZAR", "BTC");

The expected result should be 8.26 from google but it shows message Could not convert


Solution

  • I have found a way to do thiss.. just pasting my answer for someone who needed in future.

    <?php
    function convertCurrency($amount, $from, $to){
        $data = file_get_contents("https://finance.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);
    }
     convertCurrency("1", "BTC", "ZAR");
    
    
    
    function ZARtoBTC($amount){
          $BTC = convertCurrency("1", "BTC", "ZAR");
           $f_amount = number_format($amount, 3);
    
            $val = $f_amount / $BTC ;
    
           return  number_format($val, 2);
    }
    echo ZARtoBTC("100000");