Exchange rates library for PHP 5.4+
$ 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
$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. 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.
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.
You must have access to the
XigniteGlobalCurrenciesAPI. 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.
- A Symfony2 bundle FlorianvSwapBundle.