Tutorial · PHP

Currency conversion in PHP

Get exchange rates in PHP, cache them in Laravel and convert amounts without floating point errors.

Updated October 1, 2026 · 1 min read

Plain PHP with cURL

function latestRates(string $base = 'USD'): array
{
    $ch = curl_init('https://api.currencyapi.com/v3/latest?base_currency=' . urlencode($base));
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_HTTPHEADER => ['apikey: ' . getenv('CURRENCYAPI_KEY')],
        CURLOPT_TIMEOUT => 10,
    ]);
    $json = json_decode(curl_exec($ch), true);
    curl_close($ch);
    return array_map(fn ($item) => $item['value'], $json['data']);
}

$rates = latestRates('USD');
echo $rates['EUR']; // e.g. 0.8828

Laravel with caching

use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Http;

function exchangeRates(string $base = 'USD'): array
{
    return Cache::remember("fx:latest:$base", now()->addMinutes(10), function () use ($base) {
        $data = Http::withHeaders(['apikey' => config('services.currencyapi.key')])
            ->get('https://api.currencyapi.com/v3/latest', ['base_currency' => $base])
            ->throw()
            ->json('data');

        return collect($data)->map(fn ($item) => $item['value'])->all();
    });
}

Converting without float errors

// 199.99 USD to EUR with 2 decimals
$rate = (string) exchangeRates('USD')['EUR'];
$eur = bcmul('199.99', $rate, 2);

For invoices, also store the rate and its date next to the converted amount, so the conversion can be reproduced later with the historical endpoint.

Frequently asked questions

How do I get exchange rates in PHP?

Call an exchange rate API such as currencyapi with cURL or Guzzle, decode the JSON and read the rate for your currency. Cache the response so you do not call the API for every page view.

How do I avoid rounding errors with money in PHP?

Store amounts in minor units (cents) as integers, or use bcmath / a money library (moneyphp/money, brick/money) for calculations.

Exchange rate API

Get these rates in your app

currencyapi delivers real-time and historical exchange rates for 170+ currencies, crypto and metals as JSON, updated as often as every 60 seconds.

300 free requests every month. No credit card required.

GET https://api.currencyapi.com/v3/latest?base_currency=USD&currencies=EUR,GBP,JPY

{
  "meta": { "last_updated_at": "2026-09-30T23:59:59Z" },
  "data": {
    "EUR": { "code": "EUR", "value": 0.8828 },
    "GBP": { "code": "GBP", "value": 0.7556 },
    "JPY": { "code": "JPY", "value": 157.98 }
  }
}

Keep reading

Start using our Currency API for free today!

Get 300 requests / month for free