Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Exchange rates library for PHP
branch: master

README.md

Swap Build status Version

Exchange rates library for PHP 5.4+

Installation

$ composer require florianv/swap

Usage

First, you need to create an HTTP adapter provided by the egeloen/ivory-http-adapter library.

$httpAdapter = new \Ivory\HttpAdapter\FileGetContentsHttpAdapter();

Then, you can create a provider and add it to Swap:

// Create the Yahoo Finance provider
$yahooProvider = new \Swap\Provider\YahooFinanceProvider($httpAdapter);

// Create Swap with the provider
$swap = new \Swap\Swap($yahooProvider);

Quoting

To retrieve the latest exchange rate for a currency pair, you need to use the quote() method.

$rate = $swap->quote('EUR/USD');

// 1.187220
echo $rate;

// 1.187220
echo $rate->getValue();

// 15-01-11 21:30:00
echo $rate->getDate()->format('Y-m-d H:i:s');

Currencies are expressed as their ISO 4217 code.

Chaining providers

It is possible to chain providers in order to use fallbacks in case the main providers don't support the currency or are unavailable. Simply create a ChainProvider wrapping the providers you want to chain.

$chainProvider = new \Swap\Provider\ChainProvider([
    new \Swap\Provider\YahooFinanceProvider($httpAdapter),
    new \Swap\Provider\GoogleFinanceProvider($httpAdapter)
]);

The rates will be first fetched using the Yahoo Finance provider and will fallback to Google Finance.

Caching

For performance reasons you might want to cache the rates during a given time. Currently Swap allows you to use the doctrine/cache library as caching provider.

// Create the cache adapter
$cache = new \Swap\Cache\DoctrineCache(new \Doctrine\Common\Cache\ApcCache(), 3600);

// Pass the cache to Swap
$swap = new \Swap\Swap($provider, $cache);

All rates will now be cached in APC during 3600 seconds.

Currency Codes

Swap provides an enumeration of currency codes so you can use autocompletion to avoid typos.

use \Swap\Util\CurrencyCodes;

// Retrieving the EUR/USD rate
$rate = $swap->quote(new \Swap\Model\CurrencyPair(
    CurrencyCodes::ISO_EUR,
    CurrencyCodes::ISO_USD
));

Providers

  • European Central Bank Supports only EUR as base currency.
  • Google Finance Supports multiple currencies as base and quote currencies.
  • Open Exchange Rates Supports only USD as base currency for the free version and multiple ones for the enterprise version.
  • Xignite You must have access to the XigniteGlobalCurrencies API. Supports multiple currencies as base and quote currencies.
  • Yahoo Finance Supports multiple currencies as base and quote currencies.
  • WebserviceX Supports multiple currencies as base and quote currencies.
  • NationalBankOfRomania Supports only RON as base currency.

Integrations

License

MIT

Something went wrong with that request. Please try again.