Integrate Live Currency Rates into Your PHP Applications

We're thrilled to introduce our PHP SDK for CurrencyApi.net! Whether you're developing web apps, e-commerce sites, or financial tools, our SDK makes it a breeze to integrate live currency rates into your PHP projects. By the end of this guide, you'll effortlessly pull real-time currency data into your applications.

Getting Started with the PHP SDK

To get started with the CurrencyApi.net PHP SDK, ensure you have PHP 7.1 or higher installed. You can install the SDK using Composer:

composer require houseofapis/currencyapi

Installing the PHP SDK

After installation, include the SDK in your PHP project:

Using Composer

Composer is a dependency manager for PHP. It allows you to declare the libraries your project depends on and it will install them in your project for you.

If you have installed via composer, be sure you have required the autoloader in your project.

Then use the HouseOfApis\CurrencyApi\CurrencyApi class in your PHP project.

use HouseOfApis\CurrencyApi\CurrencyApi;

Manual Installation Without Composer

require_once('/path/to/currencyapi/src/CurrencyApi.php');

Creating Your PHP SDK Instance

You're now ready to start using the CurrencyApi.net PHP SDK. Begin by creating an instance of the CurrencyApi class with your API key:

<?php
use HouseOfApis\CurrencyApi\CurrencyApi;

$currencyApi = new CurrencyApi('YOUR_API_KEY');

Need a Currency API Key?

Access live exchange rates instantly with our Currency API. We offer flexible pricing plans to get you started. Sign up today and continue with the PHP tutorial!

Get Your Free API Key »

Retrieving Live Rates in PHP

Let's dive into fetching live currency rates using the following method:

$result = $currencyApi->rates();

This will return a JSON response containing all the current currency rates.

The rates() method is a convenient way to access the /rates endpoint.

Here's a complete example showcasing the API response:

$currencyApi = new CurrencyApi('YOUR_API_KEY');

try {
    $result = $currencyApi->rates();
    print_r($result);

} catch (\Exception $e) {
    print_r("An error occurred: " . $e->getMessage());
}
# Outputs
Array
(
    [valid] => 1
    [updated] => 1727622003
    [base] => USD
    [rates] => Array
        (
            [AED] => 3.673
            [AFN] => 68
            [ALL] => 88.25
            [AMD] => 387.32
            [ANG] => 1.801995
            [AOA] => 943.5
            [ARS] => 965.4662
            // ...
        )
)

Great! You've successfully retrieved live currency rates using our PHP SDK.

Available Methods for Rates Endpoint with PHP SDK

Method Description
setBase() Sets the base currency for conversions. Outputs all currency conversions for the specified currency. Default is USD.
setOutput() Specifies the response format: JSON or XML. Default is JSON.
setLimit() Limits which currency conversions are returned using the limit parameter. Comma-separated (no space) values. Optional.

Currency Conversion with PHP SDK

Easily convert amounts between currencies using our Currency API and PHP SDK. This method provides a streamlined response, optimizing performance and reducing data overhead.

The convert() method utilizes the /convert endpoint of our Currency API.

Let's convert 100 USD to GBP with the PHP SDK:

$currencyApi = new CurrencyApi('YOUR_API_KEY');

try {
    $result = $currencyApi
        ->setAmount(100)
        ->setFrom('USD')
        ->setTo('GBP')
        ->convert();

    print_r($result);
} catch (\Exception $e) {
    print_r("An error occurred: " . $e->getMessage());
}
# Outputs
Array
(
    [valid] => 1
    [updated] => 1727625603
    [conversion] => Array
        (
            [amount] => 100
            [from] => USD
            [to] => GBP
            [result] => 75.50
        )
)

As shown, the response is concise and contains only the necessary conversion details.

Available PHP SDK Methods for Convert Endpoint

Method Description
setAmount() The value of the currency you want to convert from. This should be a number and can contain a decimal place. Required.
setFrom() The currency you want to convert from. Must be a three-letter ISO 4217 currency code. Required.
setTo() The currency you want to convert to. Must be a three-letter ISO 4217 currency code. Required.
setOutput() Specifies the response format: JSON or XML. Default is JSON.

Accessing Historical Currency Rates in PHP

Need historical currency data? Our SDK provides endpoints to access past currency rates with ease.

The historical() method leverages the /historical endpoint of our Currency API.

Retrieve historical rates for USD on January 1st, 2019 using the PHP SDK:

$currencyApi = new CurrencyApi('YOUR_API_KEY');

try {
    $result = $currencyApi
        ->setDate('2019-01-01')
        ->setBase('USD')
        ->setOutput('JSON')
        ->historical();

    print_r($result);
} catch (\Exception $e) {
    print_r("An error occurred: " . $e->getMessage());
}
# Outputs
Array
(
    [valid] => 1
    [base] => USD
    [date] => 2019-01-01
    [rates] => Array
        (
            [AED] => 3.673105
            [AFN] => 75.615
            [ALL] => 107.726773
            [AMD] => 484.068111
            [ANG] => 1.770652
            [AOA] => 308.607
            [ARS] => 37.6515
            // ...
        )
)

The response provides an array with historical currency rates for the specified date.

Available Methods for Historical Endpoint

Method Description
setDate() The historical date you wish to receive the currency conversions for. Format: YYYY-MM-DD. Required.
setBase() Sets the base currency for conversions. Outputs all currency conversions for the specified currency. Default is USD.
setOutput() Specifies the response format: JSON or XML. Default is JSON.
setLimit() Limits which currency conversions are returned using the limit parameter. Comma-separated (no space) values. Optional.

Fetching Rates Over a Timeframe with PHP

Accessing currency rates over a specific timeframe enables developers to build applications that monitor currency fluctuations over time, such as financial dashboards, analytics tools, and more.

The timeframe() method utilizes the /timeframe endpoint of our Currency API.

Retrieve rates for GBP between January 1st, 2019 and January 5th, 2019 using the PHP SDK:

$currencyApi = new CurrencyApi('YOUR_API_KEY');

try {
    $result = $currencyApi
        ->setStartDate('2019-01-01')
        ->setEndDate('2019-01-05')
        ->setBase('GBP')
        ->setLimit('USD,BTC')
        ->setOutput('XML')
        ->timeframe();

    print_r($result);
} catch (\Exception $e) {
    print_r("An error occurred: " . $e->getMessage());
}
# Outputs
Array
(
    [valid] => 1
    [base] => GBP
    [start_date] => 2019-01-01
    [end_date] => 2019-01-05
    [rates] => Array
        (
            [2019-01-01] => Array
                (
                    [USD] => 1.30
                    [BTC] => 0.005
                )
            [2019-01-02] => Array
                (
                    [USD] => 1.31
                    [BTC] => 0.0051
                )
            // ...
        )
)

The response provides an array with currency rates over the specified timeframe, simplifying the process of tracking currency trends.

Available Methods for Timeframe Endpoint

Method Description
setStartDate() The start date for the currency rate timeframe. Format: YYYY-MM-DD. Required.
setEndDate() The end date for the currency rate timeframe. Format: YYYY-MM-DD. Required.
setBase() Sets the base currency for conversions. Outputs all currency conversions for the specified currency. Default is USD.
setOutput() Specifies the response format: JSON or XML. Default is JSON.
setLimit() Limits which currency conversions are returned using the limit parameter. Comma-separated (no space) values. Optional.

Best Practices for PHP Integration

To ensure a smooth and efficient integration with the PHP SDK, adhere to the following best practices:

  • Cache API responses when appropriate to minimize redundant API calls and enhance performance.
  • Implement robust error handling to gracefully manage unexpected issues and maintain application stability.
  • Securely store your API key using environment variables or configuration files that are excluded from version control.
  • Regularly consult the official documentation for updates and advanced usage techniques.

Handling API Responses in PHP SDK

Working with JSON Responses

By default, the SDK returns responses in JSON format. This makes it straightforward to work with the data directly within your PHP applications.

Working with XML Responses

You can opt for XML responses by specifying the output parameter. Here's how to retrieve and handle XML responses:

$currencyApi = new CurrencyApi('YOUR_API_KEY');

try {
    $result = $currencyApi
        ->setOutput('XML')
        ->rates();
    print_r($result);
} catch (\Exception $e) {
    print_r("An error occurred: " . $e->getMessage());
}
# Outputs
<?xml version="1.0" encoding="utf-8"?>
<root>
    <valid>true</valid>
    <updated>1727720883</updated>
    <base>USD</base>
    <rates>
        <AED>3.673</AED>
        <AFN>68</AFN>
        <ALL>88.25</ALL>
        <AMD>387.29</AMD>
        <ANG>1.80184</ANG>
        <AOA>943</AOA>
        <ARS>968.7457</ARS>
        <!-- ... -->
    </rates>
</root>

To process the XML response in PHP, you can use the SimpleXML extension:

$currencyApi = new CurrencyApi('YOUR_API_KEY');

try {
    $xmlResult = $currencyApi
        ->setOutput('XML')
        ->rates();

    $xml = simplexml_load_string($xmlResult);
    if ($xml === false) {
        throw new Exception("Failed to parse XML.");
    }

    echo "Base Currency: " . $xml->base . "\n";
    foreach ($xml->rates->children() as $currency => $rate) {
        echo "Currency: {$currency}, Rate: {$rate}\n";
    }
} catch (\Exception $e) {
    echo "An error occurred: " . $e->getMessage();
}
# Outputs
Base Currency: USD
Currency: AED, Rate: 3.673
Currency: AFN, Rate: 68
Currency: ALL, Rate: 88.25
Currency: AMD, Rate: 387.29
Currency: ANG, Rate: 1.80184
Currency: AOA, Rate: 943
Currency: ARS, Rate: 968.7457
// ...

Iterating Through JSON Responses in PHP

To iterate through the JSON response and utilize the data effectively in your application:

$currencyApi = new CurrencyApi('YOUR_API_KEY');

try {
    $result = $currencyApi->rates();
    echo "Base Currency: " . $result['base'] . "\n";
    foreach ($result['rates'] as $currency => $rate) {
        echo "{$currency}: {$rate}\n";
    }
} catch (\Exception $e) {
    echo "An error occurred: " . $e->getMessage();
}
# Outputs
Base Currency: USD
AED: 3.673
AFN: 68
ALL: 88.25
AMD: 387.29
ANG: 1.80184
AOA: 943
ARS: 968.7109
// ...

Error Handling in PHP SDK

Effective error handling ensures your application remains resilient and provides meaningful feedback to users:

$currencyApi = new CurrencyApi('YOUR_API_KEY');

try {
    $result = $currencyApi->rates();
    print_r($result);
} catch (\Exception $e) {
    print_r("An error occurred: " . $e->getMessage());
}

Integrating PHP SDK into Your Application

Integrate the CurrencyApi.net PHP SDK seamlessly into your PHP applications, whether you're building MVC frameworks like Laravel, content management systems, or custom PHP scripts.

Here's an example of a simple currency converter function within a PHP application:

function convertCurrency(CurrencyApi $currencyApi, $amount, $fromCurrency, $toCurrency) {
    try {
        $result = $currencyApi
            ->setAmount($amount)
            ->setFrom($fromCurrency)
            ->setTo($toCurrency)
            ->convert();

        return $result['conversion']['result'];
    } catch (\Exception $e) {
        throw new Exception("Conversion failed: " . $e->getMessage());
    }
}

$currencyApi = new CurrencyApi('YOUR_API_KEY');

try {
    $converted = convertCurrency($currencyApi, 100, 'BTC', 'USD');
    print_r("100 BTC is equal to {$converted} USD");
} catch (\Exception $e) {
    print_r($e->getMessage());
}

Conclusion

The CurrencyApi.net PHP SDK offers a straightforward and efficient method to integrate live currency rates into your PHP applications. With easy setup, comprehensive documentation, and dependable support, enhancing your projects with up-to-date currency data has never been easier.

Other Useful Links:

Explore Other SDKs

Not working with PHP? Explore our other SDKs tailored for different programming languages:

Python SDK

Effortlessly incorporate live currency data into your Python applications with our intuitive SDK. Access real-time exchange rates, currency conversions, and more.

Explore the Python SDK →

GoLang SDK

Quickly implement currency data into your GoLang applications with our user-friendly SDK. Access live exchange rates, currency conversions, and more.

Explore the GoLang SDK →

NodeJS SDK

Integrate real-time currency services into your NodeJS projects. Our SDK provides you with powerful tools for handling currency data with minimal effort.

Discover the NodeJS SDK →

Get Started with CurrencyApi.net Today!

Sign up now to access live currency rates and enhance your PHP applications.

View Pricing & Plans »
Meet the Author
Oli Girling

Oli Girling

Founder & Senior Software Engineer

London, UK

Connect on LinkedIn