PHP Examples
Complete PHP examples for integrating OpenFXRates into your application using cURL and Guzzle.
Installation
Using cURL (Built-in)
cURL comes built-in with PHP. Ensure it's enabled in your php.ini:
extension=curl
Using Guzzle (Recommended)
Install via Composer:
composer require guzzlehttp/guzzle
Example 1: Get Latest Rates (cURL)
Fetch the latest exchange rates using native PHP cURL:
<?php
// Configuration
$apiKey = 'your-api-key-here';
$baseUrl = 'https://api.openfxrates.com';
// Prepare request
$url = $baseUrl . '/latest_rates?base=USD&targets=EUR,GBP,JPY';
// Initialize cURL
$ch = curl_init($url);
// Set cURL options
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'X-API-Key: ' . $apiKey,
'Content-Type: application/json'
]);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
// Execute request
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
// Close cURL connection
curl_close($ch);
// Handle response
if ($httpCode === 200) {
$data = json_decode($response, true);
echo "Base Currency: " . $data['base'] . "\n";
echo "Date: " . $data['date'] . "\n";
echo "Rates:\n";
foreach ($data['rates'] as $currency => $rate) {
echo " $currency: " . number_format($rate, 4) . "\n";
}
} else {
echo "Error: HTTP $httpCode\n";
echo $response . "\n";
}
Example 2: Get Latest Rates (Guzzle)
Same request using Guzzle HTTP client:
<?php
require 'vendor/autoload.php';
use GuzzleHttp\Client;
use GuzzleHttp\Exception\GuzzleException;
// Configuration
$apiKey = 'your-api-key-here';
try {
// Create Guzzle client
$client = new Client([
'base_uri' => 'https://api.openfxrates.com',
'timeout' => 30,
]);
// Make request
$response = $client->request('GET', '/latest_rates', [
'query' => [
'base' => 'USD',
'targets' => 'EUR,GBP,JPY'
],
'headers' => [
'X-API-Key' => $apiKey,
]
]);
// Parse response
$data = json_decode($response->getBody(), true);
echo "Base Currency: " . $data['base'] . "\n";
echo "Date: " . $data['date'] . "\n";
echo "Rates:\n";
foreach ($data['rates'] as $currency => $rate) {
echo " $currency: " . number_format($rate, 4) . "\n";
}
} catch (GuzzleException $e) {
echo "Request Error: " . $e->getMessage() . "\n";
}
Example 3: Convert Currency
Convert an amount from one currency to multiple target currencies:
<?php
$apiKey = 'your-api-key-here';
$baseUrl = 'https://api.openfxrates.com';
// Conversion parameters
$from = 'USD';
$to = 'EUR,GBP,JPY';
$amount = 100;
// Build URL
$url = $baseUrl . '/convert?' . http_build_query([
'from' => $from,
'to' => $to,
'amount' => $amount
]);
// Initialize cURL
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'X-API-Key: ' . $apiKey
]);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Execute
$response = curl_exec($ch);
curl_close($ch);
// Parse and display
$data = json_decode($response, true);
echo "Converting: $amount $from\n";
echo "Results:\n";
foreach ($data['conversions'] as $currency => $convertedAmount) {
echo " $currency: " . number_format($convertedAmount, 2) . "\n";
}
Example 4: Get Historical Rates
Fetch exchange rates for a specific date:
<?php
$apiKey = 'your-api-key-here';
$baseUrl = 'https://api.openfxrates.com';
// Historical date
$date = '2024-01-15';
$base = 'USD';
$url = $baseUrl . '/historical_rates?' . http_build_query([
'base' => $base,
'date' => $date,
'targets' => 'EUR,GBP'
]);
// Initialize cURL
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'X-API-Key: ' . $apiKey
]);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Execute
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($httpCode === 200) {
$data = json_decode($response, true);
echo "Historical Rates for " . $data['date'] . "\n";
echo "Base: " . $data['base'] . "\n";
echo "Rates:\n";
foreach ($data['rates'] as $currency => $rate) {
echo " $currency: " . number_format($rate, 4) . "\n";
}
} else {
$error = json_decode($response, true);
echo "Error: " . $error['error'] . "\n";
}
Example 5: List All Currencies
Fetch all available currencies:
<?php
$apiKey = 'your-api-key-here';
$baseUrl = 'https://api.openfxrates.com';
$url = $baseUrl . '/currencies';
// Initialize cURL
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'X-API-Key: ' . $apiKey
]);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Execute
$response = curl_exec($ch);
curl_close($ch);
// Parse and display
$data = json_decode($response, true);
echo "Available Currencies: " . count($data['currencies']) . "\n\n";
foreach ($data['currencies'] as $currency) {
echo $currency['code'] . " - " . $currency['name'];
if (isset($currency['symbol'])) {
echo " (" . $currency['symbol'] . ")";
}
echo "\n";
}
Example 6: Error Handling
Comprehensive error handling for API requests:
<?php
class OpenFXRatesClient {
private $apiKey;
private $baseUrl = 'https://api.openfxrates.com';
public function __construct($apiKey) {
$this->apiKey = $apiKey;
}
public function getLatestRates($base, $targets = null) {
$params = ['base' => $base];
if ($targets) {
$params['targets'] = $targets;
}
return $this->makeRequest('/latest_rates', $params);
}
private function makeRequest($endpoint, $params = []) {
$url = $this->baseUrl . $endpoint . '?' . http_build_query($params);
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'X-API-Key: ' . $this->apiKey
]);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$curlError = curl_error($ch);
curl_close($ch);
// Handle cURL errors
if ($curlError) {
throw new Exception("Request failed: $curlError");
}
// Handle HTTP errors
if ($httpCode !== 200) {
$error = json_decode($response, true);
$message = $error['message'] ?? 'Unknown error';
throw new Exception("HTTP $httpCode: $message");
}
return json_decode($response, true);
}
}
// Usage
try {
$client = new OpenFXRatesClient('your-api-key');
$rates = $client->getLatestRates('USD', 'EUR,GBP,JPY');
print_r($rates);
} catch (Exception $e) {
echo "Error: " . $e->getMessage() . "\n";
}
Example 7: Caching Rates
Cache rates to avoid unnecessary API calls:
<?php
class CachedOpenFXRatesClient {
private $client;
private $cacheDir = './cache';
private $cacheTTL = 3600; // 1 hour
public function __construct($client) {
$this->client = $client;
if (!is_dir($this->cacheDir)) {
mkdir($this->cacheDir, 0755, true);
}
}
public function getLatestRates($base, $targets = null) {
$cacheKey = 'rates_' . $base . '_' . ($targets ?? 'all');
$cachePath = $this->cacheDir . '/' . $cacheKey . '.json';
// Check cache
if (file_exists($cachePath)) {
$cacheTime = filemtime($cachePath);
if (time() - $cacheTime < $this->cacheTTL) {
return json_decode(file_get_contents($cachePath), true);
}
}
// Fetch from API
$rates = $this->client->getLatestRates($base, $targets);
// Save to cache
file_put_contents($cachePath, json_encode($rates));
return $rates;
}
}
// Usage
$client = new OpenFXRatesClient('your-api-key');
$cached = new CachedOpenFXRatesClient($client);
$rates = $cached->getLatestRates('USD', 'EUR,GBP');
Best Practices
- Use Environment Variables - Store API keys in environment variables, not in code
- Error Handling - Always handle API errors gracefully
- Caching - Cache rates to reduce API calls
- Timeouts - Set reasonable timeouts for requests
- Validation - Validate currency codes before requesting
- Rate Limiting - Monitor rate limit headers and back off when needed
Next Steps
- JavaScript Examples → - Frontend and Node.js examples
- Python Examples → - Python and data science examples
- API Reference → - Full endpoint documentation