PHPackages                             php-core/exchange-sdk - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [API Development](/categories/api)
4. /
5. php-core/exchange-sdk

ActiveLibrary[API Development](/categories/api)

php-core/exchange-sdk
=====================

A PHP SDK for the currency exchange rates API with fallback support

1.0.1(11mo ago)0916MITPHPPHP &gt;=7.4

Since Jul 29Pushed 11mo agoCompare

[ Source](https://github.com/php-core/exchange-sdk)[ Packagist](https://packagist.org/packages/php-core/exchange-sdk)[ RSS](/packages/php-core-exchange-sdk/feed)WikiDiscussions main Synced 2d ago

READMEChangelog (2)Dependencies (5)Versions (3)Used By (0)

PHP Exchange Rate SDK
=====================

[](#php-exchange-rate-sdk)

A PHP SDK for the [Currency Exchange API](https://github.com/fawazahmed0/exchange-api). This package provides an easy-to-use interface to fetch current and historical exchange rates with built-in fallback support.

Features
--------

[](#features)

- 🚀 Easy to use static methods
- 💪 Built-in fallback support between JSDelivr and Cloudflare endpoints
- 📅 Support for historical exchange rates
- 🔄 Automatic retry with minified and regular JSON formats
- ⚡ Fast and reliable with multiple CDN options
- 🛠 Configurable endpoint preferences
- 🔍 Comprehensive error handling
- 💾 PSR-16 compatible caching support
- ⚙️ Customizable HTTP client configuration

Installation
------------

[](#installation)

Install the package via Composer:

```
composer require php-core/exchange-sdk
```

Quick Start
-----------

[](#quick-start)

```
use PHPCore\ExchangeSDK\Exchange;

// Get latest USD rates
$usdRates = Exchange::getLatestRates('usd');

// Get EUR/USD rate
$eurUsdRate = Exchange::getLatestRate('eur', 'usd');

// Get historical rates
$historicalRates = Exchange::getHistoricalRates('2024-03-06', 'usd');
```

Usage Examples
--------------

[](#usage-examples)

### Getting Latest Exchange Rates

[](#getting-latest-exchange-rates)

```
use PHPCore\ExchangeSDK\Exchange;

// Get all rates for USD
$usdRates = Exchange::getLatestRates('usd');
// Returns: ['date' => '2024-03-06', 'usd' => ['eur' => 0.85, 'gbp' => 0.73, ...]]

// Get specific currency pair rate
$eurUsdRate = Exchange::getLatestRate('eur', 'usd');
// Returns: 1.18 (float)
```

### Getting Historical Rates

[](#getting-historical-rates)

```
// Get historical rates for a specific date
$historicalRates = Exchange::getHistoricalRates('2024-03-06', 'usd');
// Returns: ['date' => '2024-03-06', 'usd' => ['eur' => 0.84, ...]]

// Get historical rate for a specific currency pair
$historicalEurUsd = Exchange::getHistoricalRate('2024-03-06', 'eur', 'usd');
// Returns: 1.08854773 (float)
```

### Configuring Endpoints

[](#configuring-endpoints)

```
// Set Cloudflare as the preferred endpoint globally
Exchange::setPreferredEndpoint(Exchange::ENDPOINT_CLOUDFLARE);

// Or use a specific endpoint for a single call
$rates = Exchange::getLatestRates('usd', Exchange::ENDPOINT_JSDELIVR);
```

### Caching Support

[](#caching-support)

The SDK supports PSR-16 Simple Cache for storing exchange rates. By default, it uses Symfony's FilesystemAdapter.

#### Default Cache Configuration

[](#default-cache-configuration)

```
// Initialize with default filesystem cache (24-hour TTL)
Exchange::initCache();

// Rates will be automatically cached
$rates = Exchange::getLatestRates('usd');
```

#### Custom Cache Configuration

[](#custom-cache-configuration)

```
use Symfony\Component\Cache\Adapter\FilesystemAdapter;
use Symfony\Component\Cache\Psr16Cache;

// Create a custom filesystem cache
$filesystemAdapter = new FilesystemAdapter(
    'exchange-rates',    // namespace
    3600,               // TTL (1 hour)
    '/path/to/cache'    // custom directory
);
$cache = new Psr16Cache($filesystemAdapter);

// Initialize SDK with custom cache
Exchange::initCache($cache);
```

#### Using Redis Cache

[](#using-redis-cache)

```
use Symfony\Component\Cache\Adapter\RedisAdapter;
use Symfony\Component\Cache\Psr16Cache;

$redis = RedisAdapter::createConnection('redis://localhost');
$cache = new Psr16Cache(new RedisAdapter($redis));

Exchange::initCache($cache, 3600); // Cache for 1 hour
```

#### Cache Management

[](#cache-management)

```
// Clear the cache
Exchange::clearCache();
```

### Custom HTTP Client Configuration

[](#custom-http-client-configuration)

```
use GuzzleHttp\Client;

// Configure custom Guzzle client
$client = new Client([
    'timeout' => 15,
    'connect_timeout' => 10,
    'headers' => [
        'User-Agent' => 'MyApp/1.0'
    ]
]);

Exchange::setClient($client);
```

Available Methods
-----------------

[](#available-methods)

### Main Methods

[](#main-methods)

- `getLatestRates(string $baseCurrency, ?string $endpoint = null): ?array`
- `getHistoricalRates(string $date, string $baseCurrency, ?string $endpoint = null): ?array`
- `getLatestRate(string $fromCurrency, string $toCurrency, ?string $endpoint = null): ?float`
- `getHistoricalRate(string $date, string $fromCurrency, string $toCurrency, ?string $endpoint = null): ?float`

### Configuration Methods

[](#configuration-methods)

- `setPreferredEndpoint(string $endpoint): void`
- `initCache(?CacheInterface $cache = null, int $ttl = 86400): void`
- `setClient(Client $client): void`
- `clearCache(): void`
- `clearClient(): void`

Endpoint Constants
------------------

[](#endpoint-constants)

- `Exchange::ENDPOINT_JSDELIVR` - Use JSDelivr CDN (default)
- `Exchange::ENDPOINT_CLOUDFLARE` - Use Cloudflare Pages

Error Handling
--------------

[](#error-handling)

The SDK handles various error scenarios gracefully:

```
// All methods return null on failure
$rates = Exchange::getLatestRates('invalid_currency');
if ($rates === null) {
    // Handle error
}

// Invalid endpoint configuration throws Exception
try {
    Exchange::setPreferredEndpoint('invalid_endpoint');
} catch (Exception $e) {
    // Handle error
}
```

Fallback Mechanism
------------------

[](#fallback-mechanism)

The SDK implements a robust fallback mechanism:

1. Try preferred endpoint
2. If preferred endpoint fails, try fallback endpoint
3. Results are cached for subsequent requests
4. Cache duration is configurable

Testing
-------

[](#testing)

Run the test suite with PHPUnit:

```
./vendor/bin/phpunit
```

Requirements
------------

[](#requirements)

- PHP 7.4 or higher
- Guzzle HTTP Client 7.0 or higher
- PSR-16 Simple Cache implementation

License
-------

[](#license)

MIT License. See LICENSE file for details.

Contributing
------------

[](#contributing)

Contributions are welcome! Please feel free to submit a Pull Request.

Credits
-------

[](#credits)

This package is a wrapper for the [Currency Exchange API](https://github.com/fawazahmed0/exchange-api) by [Fawaz Ahmed](https://github.com/fawazahmed0).

###  Health Score

30

—

LowBetter than 62% of packages

Maintenance52

Moderate activity, may be stable

Popularity17

Limited adoption so far

Community2

Small or concentrated contributor base

Maturity38

Early-stage or recently created project

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~0 days

Total

2

Last Release

340d ago

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/103283996?v=4)[PHP Core](/maintainers/php-core)[@php-core](https://github.com/php-core)

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/php-core-exchange-sdk/health.svg)

```
[![Health](https://phpackages.com/badges/php-core-exchange-sdk/health.svg)](https://phpackages.com/packages/php-core-exchange-sdk)
```

###  Alternatives

[laravel/framework

The Laravel Framework.

34.8k543.8M20.1k](/packages/laravel-framework)[shopware/platform

The Shopware e-commerce core

3.4k1.5M3](/packages/shopware-platform)[tempest/framework

The PHP framework that gets out of your way.

2.2k34.4k15](/packages/tempest-framework)[shopware/core

Shopware platform is the core for all Shopware ecommerce products.

585.6M574](/packages/shopware-core)[oro/platform

Business Application Platform (BAP)

645143.5k115](/packages/oro-platform)[tencentcloud/tencentcloud-sdk-php

TencentCloudApi php sdk

3741.3M45](/packages/tencentcloud-tencentcloud-sdk-php)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
