How to get live (spot) gold price using API in PHP?

< Back to Blog

PHP is a general-purpose scripting language geared towards web development. To get live gold price 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 to use by signing up at Metalpriceapi.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 gold price

<?php

$curl = curl_init();

curl_setopt_array($curl, array(
  CURLOPT_URL => 'https://api.metalpriceapi.com/v1/latest?api_key=REPLACE_ME&base=USD&currencies=XAU,XAG,EUR',
  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 gold price

<?php
require_once 'HTTP/Request2.php';
$request = new HTTP_Request2();
$request->setUrl('https://api.metalpriceapi.com/v1/latest?api_key=REPLACE_ME&base=USD&currencies=XAU,XAG,EUR');
$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 gold price

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

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