Currency Conversion using PHP

Currency Conversion using PHP

  1. Blog
  2. 15 November 2026
  3. 3 min read

Stefan Bogdanescu

Founder & Senior Architect

Currency Conversion using PHP

Building a currency converter is a classic use case for integrating third-party financial APIs. The core requirement is straightforward: accept an amount and a source currency, then return the equivalent value in a target currency. However, the implementation details vary significantly depending on whether you prioritize cost, latency, or data freshness.

To handle this in PHP, you first need to identify a reliable data provider. Popular choices include the European Central Bank (ECB) for free, low-volume needs; OpenExchangeRates for developer-friendly endpoints with generous free tiers; and major banks like Wise or Revolut which often provide public APIs but may require stricter rate limiting checks. Once an API is selected, the workflow involves sending a GET request to their exchange rates endpoint, parsing the JSON response, and performing the multiplication in your application logic.

Here is a practical example using a generic cURL approach with PHP 8.0+. This snippet assumes you have a valid API key from a provider like OpenExchangeRates.

<?php
$apiKey = 'YOUR_API_KEY_HERE';
$amount = 100;
$fromCurrency = 'USD';
$toCurrency = 'AUD';

// Fetch current exchange rates
$url = "https://openexchangerates.org/api/latest.json?app_id={$apiKey}";

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);

$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

if ($httpCode === 200) {
    $data = json_decode($data, true);
    
    // Validate that the target currency exists in the response
    if (isset($data['rates'][$toCurrency])) {
        $rate = $data['rates'][$toCurrency];
        $convertedAmount = $amount * $rate;
        
        echo "Converted Amount: {$convertedAmount} {$toCurrency}";
    } else {
        throw new RuntimeException("Target currency not found in API response.");
    }
} else {
    // Handle specific error cases (e.g., 401 Unauthorized, 429 Rate Limited)
    echo "Failed to fetch rates. HTTP Code: {$httpCode}";
}

When selecting an API, you must weigh the trade-off between update frequency and cost. The ECB updates its data daily at a specific time (usually 16:00 CET), meaning your conversion rate is static for that entire day. This is acceptable for non-financial instruments but fails for high-frequency trading or real-time dashboards where users expect millisecond-level accuracy. Conversely, commercial APIs like OpenExchangeRates offer multiple endpoints (latest, history, and convert) that allow you to fetch rates closer to the moment of the request, though this usually incurs a cost per call once you exceed your free tier limits.

A common pitfall in implementation is ignoring rate limiting. Most free tiers limit requests to 100 per day or minute. If your application receives high traffic, a single user hitting the "Convert" button repeatedly could quickly exhaust your quota, causing subsequent requests to fail with a 429 Too Many Requests status code. You should always implement exponential backoff retry logic or cache the exchange rates for a short duration (e.g., 5–10 minutes) to reduce API calls.

Additionally, you must handle floating-point precision carefully. Currency calculations often result in long decimals (e.g., 43.21987654). Displaying this to a user looks unprofessional and can cause confusion. Always round the final result to two decimal places before output, using round($convertedAmount, 2) in PHP.

If your project is built on Laravel, you might consider leveraging existing packages that abstract these cURL calls, such as those available via Composer, or integrating with services like LaravelCompany for specific financial toolkits if they align with your architecture. Regardless of the stack, ensuring you validate the API response structure and handle exceptions gracefully is essential for a production-ready currency converter.

Our network