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.
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
After installation, include the SDK in your PHP project:
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;
require_once('/path/to/currencyapi/src/CurrencyApi.php');
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');
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 »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.
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. |
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.
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. |
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.
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. |
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.
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. |
To ensure a smooth and efficient integration with the PHP SDK, adhere to the following best practices:
By default, the SDK returns responses in JSON format. This makes it straightforward to work with the data directly within your PHP applications.
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
// ...
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
// ...
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());
}
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());
}
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.
Not working with PHP? Explore our other SDKs tailored for different programming languages:
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 →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 →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 →Sign up now to access live currency rates and enhance your PHP applications.
View Pricing & Plans »