PHP code example of otherguy / php-currency-api

1. Go to this page and download the library: Download otherguy/php-currency-api library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

otherguy / php-currency-api example snippets


use Otherguy\Currency\Currency;
use Otherguy\Currency\DriverFactory;

$result = DriverFactory::make('frankfurter')
    ->from(Currency::USD)
    ->to([Currency::EUR, Currency::GBP])
    ->get();

echo $result->rate(Currency::EUR);     // BigDecimal '0.92'
echo $result->convert(100, Currency::USD, Currency::EUR); // BigDecimal '92.00'

use GuzzleHttp\Client;
use Http\Factory\Guzzle\RequestFactory;
use Otherguy\Currency\DriverFactory;

$factory = new DriverFactory();
$driver  = $factory->build('fixerio', new Client(), new RequestFactory());

$result = $driver->accessKey('YOUR_KEY')
    ->from(Currency::EUR)
    ->to(Currency::USD)
    ->get();

use Nyholm\Psr7\Factory\Psr17Factory;
use Otherguy\Currency\DriverFactory;
use Symfony\Component\HttpClient\Psr18Client;

$psr17  = new Psr17Factory();
$client = new Psr18Client();

$driver = (new DriverFactory())->build('frankfurter', $client, $psr17);

use Otherguy\Currency\Currency;

Currency::USD->value;          // 'USD'
Currency::USD->displayName();  // 'United States Dollar'
Currency::tryFromCode('EUR');  // Currency::EUR
Currency::tryFromCode('XYZ');  // null
Currency::cases();             // every supported currency

$driver->accessKey('YOUR_KEY');

$driver->config('format', '1'); // CurrencyLayer pretty-printed JSON

$driver->from(Currency::USD);
$driver->source('USD');

$driver->to(Currency::BTC);
$driver->currencies([Currency::BTC, Currency::EUR, Currency::USD]);
$driver->to([Currency::EUR, Currency::GBP]);

$driver->get();              // current rates for the configured target currencies
$driver->get(Currency::DKK); // current rate for DKK

use DateTimeImmutable;

$driver->date(new DateTimeImmutable('2010-01-01'))->historical();
$driver->historical(new DateTimeImmutable('2018-07-01'));

$driver->convert(10.00, Currency::USD, Currency::THB);
$driver->convert(122.50, Currency::NPR, Currency::EUR, new DateTimeImmutable('2019-01-01'));

DriverFactory::make('fixerio')->from(Currency::USD)->to(Currency::EUR)->get();
DriverFactory::make('fixerio')->from(Currency::USD)->to(Currency::NPR)->date(new DateTimeImmutable('2013-03-02'))->historical();
DriverFactory::make('fixerio')->from(Currency::USD)->to(Currency::NPR)->amount(12.10)->convert();

use Brick\Math\BigDecimal;

$result = DriverFactory::make('frankfurter')
    ->from(Currency::USD)
    ->to([Currency::EUR, Currency::GBP])
    ->get();

$result->all();                     // ['USD' => BigDecimal '1', 'EUR' => BigDecimal '0.89', 'GBP' => BigDecimal '0.79']
$result->allAsFloats();             // legacy float view
$result->getBaseCurrency();         // 'USD'
$result->getDate();                 // '2026-04-25'
$result->rate(Currency::EUR);       // BigDecimal '0.89'
$result->rateAsFloat(Currency::EUR);// 0.89

$result->convert(5.0, Currency::EUR, Currency::USD); // BigDecimal '5.618...'

$rebased = $result->setBaseCurrency(Currency::EUR);
$rebased->getBaseCurrency();        // 'EUR'
$rebased->originalBaseCurrency;     // 'USD' — readonly, never mutated

use Otherguy\Currency\DriverFactory;

$factory = new DriverFactory();
$factory->register('mybank', \Acme\MyBankDriver::class);

$driver = $factory->build('mybank');



declare(strict_types=1);

namespace Otherguy\Currency\Drivers;

use Brick\Math\BigDecimal;
use Brick\Math\RoundingMode;
use DateTimeInterface;
use Otherguy\Currency\Currency;
use Otherguy\Currency\Exceptions\ApiException;
use Otherguy\Currency\Results\ConversionResult;
use Override;

class MyProvider extends BaseCurrencyDriver
{
    protected string $apiURL       = 'api.myprovider.example/v1';
    protected string $protocol     = 'https';
    protected string $baseCurrency = 'USD';

    #[Override]
    public function get(string|Currency|array $forCurrency = []): ConversionResult
    {
        if ($forCurrency !== []) {
            $this->currencies($forCurrency);
        }

        $response = $this->apiRequest('latest', [
            'base'    => $this->getBaseCurrency(),
            'symbols' => implode(',', $this->getSymbols()),
        ]);

        return new ConversionResult(
            (string) $response['base'],
            (string) $response['date'],
            $response['rates'],
        );
    }

    #[Override]
    public function historical(
        ?DateTimeInterface $date = null,
        string|Currency|array $forCurrency = [],
    ): ConversionResult {
        if ($date instanceof DateTimeInterface) {
            $this->date($date);
        }
        if ($forCurrency !== []) {
            $this->currencies($forCurrency);
        }
        if ($this->getDate() === null) {
            throw new ApiException('Date is dedBy(BigDecimal::of((string) $this->amount), ConversionResult::DEFAULT_SCALE, RoundingMode::HalfUp);

        return new ConversionResult(
            $this->getBaseCurrency(),
            isset($response['date']) ? (string) $response['date'] : null,
            [$target => $rate],
        );
    }
}

#[\Override]
public function accessKey(string $accessKey): static
{
    return $this->config('apikey', $accessKey);
}

#[\Override]
public function accessKey(string $accessKey): static
{
    $this->httpHeaders['apikey'] = $accessKey;

    return $this;
}

#[\Override]
public function accessKey(string $accessKey): static
{
    throw new ApiException('MyProvider does not 

#[\Override]
protected function apiRequest(string $endpoint, array $params = []): array
{
    $response = parent::apiRequest($endpoint, $params);

    if (($response['success'] ?? null) !== true) {
        $info = (string) ($response['error']['info'] ?? 'Unknown API error.');
        throw new ApiException($info);
    }

    return $response;
}

public function __construct(?array $drivers = null)
{
    $this->drivers = $drivers ?? [
        // ...
        'myprovider' => MyProvider::class,
    ];
}

use Otherguy\Currency\Currency;
use Otherguy\Currency\Tests\Support\DriverHarness;
use Otherguy\Currency\Tests\Support\JsonResponse;
use PHPUnit\Framework\Attributes\Test;
use PHPUnit\Framework\TestCase;

class MyProviderTest extends TestCase
{
    private DriverHarness $harness;

    protected function setUp(): void
    {
        $this->harness = new DriverHarness();
    }

    #[Test]
    public function get_parses_provider_envelope(): void
    {
        $this->harness->http->enqueue(JsonResponse::ok(json_encode([
            'base'  => 'USD',
            'date'  => '2026-04-01',
            'rates' => ['EUR' => 0.92],
        ], JSON_THROW_ON_ERROR)));

        $result = $this->harness->make('myprovider')
            ->accessKey('test-key')
            ->from(Currency::USD)
            ->to(Currency::EUR)
            ->get();

        $this->assertSame('0.92', (string) $result->rate(Currency::EUR));

        $request = $this->harness->http->lastRequest();
        $this->assertNotNull($request);
        $this->assertStringContainsString('apikey=test-key', $request->getUri()->getQuery());
    }
}

use Otherguy\Currency\Drivers\MockCurrencyDriver;
use Otherguy\Currency\DriverFactory;

$driver = DriverFactory::make('mock');
assert($driver instanceof MockCurrencyDriver);

$driver->withRates(['EUR' => '0.92', 'GBP' => '0.79']);

$driver->get()->rate('EUR'); // BigDecimal '0.92'
bash
composer