Search code examples
phptype-conversionrates

trouble Currency conversion formula


I have database with a list of currencies and their rates, also i have the history for them as well, the base rate is usd,

now the question is my user select a different base rate ie AED, EGP, BRL

I need to convert all my values dynamically on that base rate user has selected.

Q: what is the formula for rate conversion and is there a php or mysql way of doing this.

I have search high and low for this and i keep getting stomped


Solution

  • An extremely simple way of doing this would be to use a freely available API such as appspot's rateexchange: http://rate-exchange.appspot.com/currency?from=USD&to=EGP&q=10

    Where from= the source currency, to= the target currency, and q= the amount of source currency.

    You could then easily use PHP's cURL to GET the resulting JSON, and use json_decode to convert it into usable PHP.

    Example:

    function get($url)
    { 
        $ch = curl_init ($url);
        curl_setopt ($ch, CURLOPT_RETURNTRANSFER, true);
        return curl_exec ($ch);
    }
    
    $json = get("http://rate-exchange.appspot.com/currency?from=USD&to=EUR&q=10");
    $array = json_decode($json, true);
    
    print_r($array);