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
.
REPLACE_ME
with your API key.base
value to a currency or remove this query param.currencies
value to a list of values or remove this query param.For 2 and 3, you can find this documented at Offical Documentation
<?php
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => 'https://api.metalpriceapi.com/v1/latest?api_key=REPLACE_ME&base=USD¤cies=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;
<?php
require_once 'HTTP/Request2.php';
$request = new HTTP_Request2();
$request->setUrl('https://api.metalpriceapi.com/v1/latest?api_key=REPLACE_ME&base=USD¤cies=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();
}
<?php
$client = new http\Client;
$request = new http\Client\Request;
$request->setRequestUrl('https://api.metalpriceapi.com/v1/latest?api_key=REPLACE_ME&base=USD¤cies=XAU,XAG,EUR');
$request->setRequestMethod('GET');
$request->setOptions(array());
$client->enqueue($request)->send();
$response = $client->getResponse();
echo $response->getBody();