Swap

April 29, 2026 ยท View on GitHub

Tests Psalm Total Downloads Version

The easy-to-use PHP currency conversion library. Retrieve exchange rates from 30 providers, with caching and fallback. Maintained since 2014.

Swap is a mature PHP currency conversion library for retrieving and working with exchange rates. It provides a single, easy-to-use API on top of multiple exchange rate providers, ranging from public sources (the European Central Bank, several national banks, exchangerate.host) to commercial exchange rate APIs that require an API key. Caching, historical rates, and a fallback chain are built in. Used in real-world PHP applications since 2014.

๐Ÿ’ก What is Swap?

  • Swap is a PHP library for currency conversion and exchange rate retrieval.
  • It exposes a wide range of exchange rate providers behind a common interface.
  • It caches results via PSR-16 SimpleCache.
  • It supports historical rates.
  • It supports a fallback chain. When a provider errors, the next provider in the chain is tried.

๐ŸŽฏ When should you use Swap?

  • Use Swap when you need to retrieve exchange rates in a PHP application: currency conversion workflows, multi-currency pricing, invoice totals, reconciliation, or historical FX data.
  • Use the lower-level Exchanger library when Swap's defaults are too opinionated and you want finer control over chain composition, caching, or HTTP plumbing.

Why not call an exchange rate API directly?

You can integrate a single exchange rate API directly in your application.

Swap is useful when you need more than a single provider:

  • Provider abstraction โ€” switch providers without rewriting your code
  • Fallback support โ€” if one provider fails, another can be used automatically
  • Unified interface โ€” all providers share the same API
  • Caching โ€” reduce API calls and improve performance
  • Flexibility โ€” combine public and commercial providers

For simple use cases, calling a single API may be enough.

Swap becomes valuable when you need reliability, flexibility, or long-term maintainability.

๐Ÿ“ฆ Installation

Swap requires PHP 8.2 or newer.

composer require florianv/swap symfony/http-client nyholm/psr7

symfony/http-client is the PSR-18 HTTP client and nyholm/psr7 provides the PSR-17 factories. Any PSR-18 / PSR-17 implementation works (see the documentation for alternatives such as Guzzle).

โšก Quickstart

use Swap\Builder;

// Build Swap with the European Central Bank (free, no API key required).
$swap = (new Builder())
    ->add('european_central_bank')
    ->build();

// EUR โ†’ USD exchange rate
$rate = $swap->latest('EUR/USD');

$rate->getValue();                 // e.g. 1.0823 (a float)
$rate->getDate()->format('Y-m-d'); // e.g. 2026-04-29
$rate->getProviderName();          // 'european_central_bank'

// Convert an amount using the returned rate
$amountInEUR  = 100.00;
$amountInUSD  = $amountInEUR * $rate->getValue();

// Retrieve a historical rate
$past = $swap->historical('EUR/USD', new \DateTime('-15 days'));

Swap retrieves the rate; your application multiplies the amount by $rate->getValue() to perform the conversion.

๐Ÿ” Configuring multiple providers (fallback chain)

$swap = (new Builder())
    ->add('your_primary_provider', ['api_key' => 'YOUR_KEY']) // see Providers below
    ->add('your_fallback_provider', ['api_key' => 'YOUR_KEY'])
    ->add('european_central_bank') // free fallback for EUR-base pairs
    ->build();

Providers are tried in order. If a provider does not support the requested currency pair, it is skipped silently. If a provider throws an error, the next provider is tried. If every provider fails, a ChainException is thrown with all collected errors.

๐Ÿ›  Common use cases

  • Display localized prices in multi-currency storefronts.
  • Compute invoice totals across currencies.
  • Reconcile multi-currency ledgers using historical rates.
  • Power internal FX dashboards with rate history.
  • Build currency conversion infrastructure for fintech and ERP applications.

๐Ÿงญ Which package should I use?

The Swap ecosystem is a layered toolkit for currency conversion in PHP:

  • Swap. The easy-to-use, high-level API (this package).
  • Exchanger. Lower-level, more granular alternative; direct access to the 30 provider implementations and the ExchangeRateService interface.
  • Laravel Swap. Laravel application of Swap.
  • Symfony Swap. Symfony integration of Swap.

All four packages are MIT-licensed and require PHP 8.2 or newer.

๐Ÿ“Š Providers

Start with a single provider (for example the European Central Bank), then add others as needed.

Swap supports 30 exchange rate providers via Exchanger. Pass the identifier to Builder::add().

Public providers (no API key required)

ServiceIdentifierBaseQuoteHistorical
Bulgarian National Bankbulgarian_national_bank*BGNYes
Central Bank of the Czech Republiccentral_bank_of_czech_republic*CZKYes
Central Bank of the Republic of Turkeycentral_bank_of_republic_turkey*TRYYes
Central Bank of the Republic of Uzbekistancentral_bank_of_republic_uzbekistan*UZSYes
Cryptonatorcryptonator* (crypto)* (crypto)No
European Central Bankeuropean_central_bankEUR*Yes
exchangerate.hostexchangeratehost**Yes
National Bank of Georgianational_bank_of_georgia*GELYes
National Bank of Romanianational_bank_of_romania(limited list)(limited list)Yes
National Bank of the Republic of Belarusnational_bank_of_republic_belarus*BYNYes
National Bank of Ukrainenational_bank_of_ukraine*UAHYes
Russian Central Bankrussian_central_bank*RUBYes
WebserviceXwebservicex**No

Commercial providers (require an API key)

ServiceIdentifierBaseQuoteHistorical
AbstractAPIabstract_api**Yes
coinlayercoin_layer* (crypto)*Yes
Currency Converter APIcurrency_converter**Yes
Currency Data (APILayer)apilayer_currency_dataUSD (free), * (paid)*Yes
CurrencyDataFeedcurrency_data_feed**No
currencylayer (direct)currency_layerUSD (free), * (paid)*Yes
Exchange Rates Data (APILayer)apilayer_exchange_rates_dataUSD (free), * (paid)*Yes
exchangeratesapi (direct)exchange_rates_apiUSD (free), * (paid)*Yes
fastFOREX.iofastforexUSD (free), * (paid)*No
Fixer (APILayer)apilayer_fixerEUR (free), * (paid)*Yes
Fixer (direct)fixerEUR (free), * (paid)*Yes
1Forgeforge**No
Open Exchange Ratesopen_exchange_ratesUSD (free), * (paid)*Yes
xChangeApi.comxchangeapi**Yes
Xignitexignite**Yes

You can also add your own provider by implementing the Exchanger\Contract\ExchangeRateService interface and passing the instance to Builder::addExchangeRateService().

โš™ Caching, HTTP client, and error handling

  • Caching. Swap uses PSR-16 SimpleCache. Configure once on the builder:

    $swap = (new Builder())->useSimpleCache($psr16Cache)->add('european_central_bank')->build();
    

    Disable caching for a single query: $swap->latest('EUR/USD', ['cache' => false]). Override the TTL for a single query: $swap->latest('EUR/USD', ['cache_ttl' => 3600]).

  • HTTP client. Any PSR-18 client (symfony/http-client, php-http/guzzle7-adapter, etc.) is supported and auto-discovered via php-http/discovery. To pass an explicit instance, use Builder::useHttpClient().

  • Errors. When every configured provider has either skipped (unsupported pair) or thrown, Swap raises an Exchanger\Exception\ChainException containing all collected exceptions.

๐Ÿ“š Documentation

The full documentation is in doc/readme.md, and is also published at florianv.github.io/swap.

The Swap ecosystem:

  • Swap: easy-to-use PHP currency conversion library.
  • Exchanger: lower-level, more granular alternative; direct access to provider implementations.
  • Laravel Swap: Laravel application of Swap.
  • Symfony Swap: Symfony integration of Swap.

๐Ÿค Sponsorship

The Swap ecosystem is open to selected sponsorships from exchange rate API providers and financial infrastructure companies.

Sponsorship can include:

  • Documentation visibility
  • Integration examples
  • Ecosystem-level visibility across Swap, Exchanger, Laravel Swap, and Symfony Swap

For inquiries, contact the maintainer via GitHub.

๐Ÿ™Œ Contributing

Issues and pull requests are welcome. Please see the existing issues before opening a new one.

๐Ÿ“„ License

The MIT License (MIT). Please see LICENSE for more information.

๐Ÿ‘ Credits