Exchange rates library for PHP
$ composer require florianv/swap
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);
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.
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.
For performance reasons you might want to cache the rates during a given time.
$ composer require doctrine/cache
// 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.
$ composer require illuminate/cache
// Create the cache adapter
$store = new \Illuminate\Cache\ApcStore(new \Illuminate\Cache\ApcWrapper());
$cache = new \Swap\Cache\IlluminateCache($store, 60);
// Pass the cache to Swap
$swap = new \Swap\Swap($provider, $cache);
All rates will now be cached in APC during 60 minutes.
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
));
- 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.
- National Bank of Romania Supports only RON as base currency.
Array
Retrieves rates from a PHP array
- A Symfony2 bundle FlorianvSwapBundle.
- A Laravel 5 package florianv/laravel-swap.