How to get live (spot) forex rate using API in PHP?

< Back to Guides

PHP is a general-purpose scripting language geared towards web development. To get live forex rate using PHP, we offer three sample code snippets using different method. Methods includes using cURL, HTTP_Request2, or pecl_http.

Instructions

  1. Get a free API key to use by signing up at forexrateapi.com and replace REPLACE_ME with your API key.
  2. Update base value to a currency or remove this query param.
  3. Update currencies value to a list of values or remove this query param.

For 2 and 3, you can find this documented at Offical Documentation

 

Using cURL to fetch live forex rate

<?php

$curl = curl_init();

curl_setopt_array($curl, array(
  CURLOPT_URL => 'https://api.forexrateapi.com/v1/latest?api_key=REPLACE_ME&base=USD&currencies=EUR,JPY,CAD',
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => '',
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 0,
  CURLOPT_FOLLOWLOCATION => true,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => 'GET',
));

$response = curl_exec($curl);

curl_close($curl);
echo $response;

 

Using HTTP_Request2 to fetch live forex rate

<?php
require_once 'HTTP/Request2.php';
$request = new HTTP_Request2();
$request->setUrl('https://api.forexrateapi.com/v1/latest?api_key=REPLACE_ME&base=USD&currencies=EUR,JPY,CAD');
$request->setMethod(HTTP_Request2::METHOD_GET);
$request->setConfig(array(
  'follow_redirects' => TRUE
));
try {
  $response = $request->send();
  if ($response->getStatus() == 200) {
    echo $response->getBody();
  }
  else {
    echo 'Unexpected HTTP status: ' . $response->getStatus() . ' ' .
    $response->getReasonPhrase();
  }
}
catch(HTTP_Request2_Exception $e) {
  echo 'Error: ' . $e->getMessage();
}

 

Using pecl_http to fetch live forex rate

<?php
$client = new http\Client;
$request = new http\Client\Request;
$request->setRequestUrl('https://api.forexrateapi.com/v1/latest?api_key=REPLACE_ME&base=USD&currencies=EUR,JPY,CAD');
$request->setRequestMethod('GET');
$request->setOptions(array());

$client->enqueue($request)->send();
$response = $client->getResponse();
echo $response->getBody();