To get live gold prices in PHP, send a GET to api.goldprice.dev/v1/spot/XAU-USD-SPOT with your API key in the X-API-Key header using native cURL, no Composer required. Decode the JSON, keep prices as strings, and use BCMath for exact decimal math. Cache per symbol for 60 seconds. The free tier covers 5,000 calls/month, no credit card. Tested June 2026 against PHP 8.3.
Get your goldprice.dev API key
Sign up for a free account at goldprice.dev/onboarding. After email confirmation, your dashboard shows a key starting with ga_live_. Set it as an environment variable:
export GOLDPRICE_API_KEY=ga_live_replace_with_your_key_hereThe free tier includes 5,000 calls/month and gold spot in 31 currencies. No credit card required.
Confirm the required extensions
No Composer packages are needed, curl and json ship with PHP 8, and bcmath is a standard extension for exact decimal math. Confirm all three are enabled:
php -m | grep -E '^(curl|json|bcmath)$'# curl# json# bcmath <- if missing, install php8.3-bcmath (or enable in php.ini)Write the goldprice client
Save this as goldprice.php. spot() caches per symbol for 60 seconds in a static array, retries up to 3 times on 429 with exponential backoff, and returns the decoded array with prices left as strings so BCMath can do exact arithmetic.
<?php// php: goldprice.php, native cURL + BCMath, no Composer// curl-equivalent: https://api.goldprice.dev/v1/spot/XAU-USD-SPOTdeclare(strict_types=1);const API_BASE = 'https://api.goldprice.dev';const TIMEOUT = 5; // secondsconst TTL = 60; // secondsfinal class RateLimitedException extends RuntimeException {}final class GoldpriceClient{ private string $apiKey; /** @var array<string, array{data: array, expires: int}> */ private static array $cache = []; public function __construct() { $key = getenv('GOLDPRICE_API_KEY'); if ($key === false || $key === '') { throw new RuntimeException('GOLDPRICE_API_KEY not set'); } $this->apiKey = $key; } /** * Fetch live spot price. Cached 60s per symbol, retries 3x on 429. * Prices stay as strings for BCMath. */ public function spot(string $symbol = 'XAU-USD-SPOT'): array { $now = time(); if (isset(self::$cache[$symbol]) && self::$cache[$symbol]['expires'] > $now) { return self::$cache[$symbol]['data']; } for ($attempt = 0; $attempt < 3; $attempt++) { try { $data = $this->fetch($symbol); self::$cache[$symbol] = ['data' => $data, 'expires' => $now + TTL]; return $data; } catch (RateLimitedException) { sleep(1 << $attempt); // 1s, 2s, 4s } } throw new RateLimitedException('goldprice: 429 after 3 retries'); } private function fetch(string $symbol): array { $ch = curl_init(API_BASE . '/v1/spot/' . rawurlencode($symbol)); curl_setopt_array($ch, [ CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => TIMEOUT, CURLOPT_HTTPHEADER => ['X-API-Key: ' . $this->apiKey], ]); $body = curl_exec($ch); $code = curl_getinfo($ch, CURLINFO_RESPONSE_CODE); curl_close($ch); if ($code === 429) { throw new RateLimitedException('rate limited'); } if ($code !== 200 || $body === false) { throw new RuntimeException("goldprice: unexpected status {$code}"); } return json_decode((string) $body, true, 512, JSON_THROW_ON_ERROR); }}$client = new GoldpriceClient();$r = $client->spot('XAU-USD-SPOT');// Prices are strings; use BCMath for exact math (e.g. price for 5 oz):$fiveOz = bcmul($r['price'], '5', 4);printf("%s-%s: %s (computed %s)\n", $r['symbol'], $r['quote_currency'], $r['price'], $r['computed_at']);printf("5 troy oz = %s %s\n", $fiveOz, $r['quote_currency']);Run it
From the same shell where you exported GOLDPRICE_API_KEY, run the file with the CLI. The first call hits the API; further spot() calls in the same process within 60 seconds return the cached array. The static cache lives per process, back it with APCu or Redis to share across requests under PHP-FPM.
php goldprice.php# XAU-USD: 4012.75 (computed 2026-10-23T07:00:18.221118+00:00)# 5 troy oz = 20063.7500 USDSwitch currency or metal
Symbols are METAL-CURRENCY-SPOT. Pass any of the 31 spot currencies to spot(). Each unique symbol caches independently in the static array, so a page rendering 5 symbols makes at most 5 uncached calls and reuses them on the next render within the window.
$client = new GoldpriceClient();// USD spot, default$client->spot('XAU-USD-SPOT');$client->spot('XAU-INR-SPOT');$client->spot('XAU-EUR-SPOT');// Silver in USD$client->spot('XAG-USD-SPOT');Expected output
{ "symbol": "XAU", "quote_currency": "USD", "unit": "troy_ounce", "contract_type": "spot", "price": "4012.75", "is_stale": false, "computed_at": "2026-10-23T07:00:18.221118+00:00"}The CLI prints two lines: the symbol/currency/price/timestamp, and the BCMath product for 5 troy ounces. The decoded array is what your downstream code consumes, prices stay as strings.
Common errors
| Code | What you see | Fix |
|---|---|---|
| 401 | RuntimeException: goldprice: unexpected status 401 | API key missing or invalid. Confirm the variable reaches PHP: php -r 'echo getenv("GOLDPRICE_API_KEY");'. Under PHP-FPM, CLI env vars are not shared, set the key via fastcgi_param or your process manager. If empty, re-copy it from your dashboard. |
| 429 | Three retries with backoff all return 429, then RateLimitedException is thrown | You hit the per-minute cap. The 60-second cache prevents this for steady traffic; under PHP-FPM the static cache is per request, so promote it to APCu (apcu_fetch / apcu_store) to share across requests. For sustained volume, see /pricing for paid plans. |
| N/A | Rounding errors when you cast prices to float for math | Never cast the price to (float) before arithmetic, PHP floats lose precision on summation. Keep the value as the string the API returns and use bcadd, bcmul, and bccomp with an explicit scale. Enable the bcmath extension if those functions are undefined. |
Going further
- Promote the static cache to
apcu_store/apcu_fetchso one fetch serves every PHP-FPM worker for the full 60 seconds - Add a
bars()method for/v1/bars?symbol=XAU-USD-SPOT&interval=1d&from=...&to=...and chart the rows with your template engine - Wrap
spot()in a thin Laravel or Symfony service and bind it in the container for dependency injection - Add an
If-None-Match/ ETag check if you poll the same symbol from many workers, to skip unchanged payloads - Format prices for display with
bcdivagainst troy-ounce-to-gram factors for a per-gram retail view