---
title: "Live gold prices in PHP · goldprice.dev"
description: "Call goldprice.dev from PHP with native cURL, BCMath, retry-on-429, and a 60-second cache, no Composer. Free tier: 5,000 calls/mo. Tested June 2026."
canonical: "https://goldprice.dev/tutorials/php"
---

# How to get live gold prices in PHP

Call the goldprice.dev API from PHP with native cURL, BCMath for exact math, retry-on-429, and a 60-second cache, no Composer.

26 Jun 2026 · 4 min read

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](https://goldprice.dev/onboarding). After email confirmation, your dashboard shows a key starting with `ga_live_`. Set it as an environment variable:

```bash
export GOLDPRICE_API_KEY=ga_live_replace_with_your_key_here
```

The 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:

```bash
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 title="goldprice.php"
<?php
// php: goldprice.php, native cURL + BCMath, no Composer
// curl-equivalent: https://api.goldprice.dev/v1/spot/XAU-USD-SPOT
declare(strict_types=1);

const API_BASE = 'https://api.goldprice.dev';
const TIMEOUT  = 5;   // seconds
const TTL      = 60;  // seconds

final 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.

```bash
php goldprice.php
# XAU-USD: 4012.75 (computed 2026-10-23T07:00:18.221118+00:00)
# 5 troy oz = 20063.7500 USD
```

## Switch 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.

```php title="goldprice.php · multi-currency"
$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

```json
{
  "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](https://goldprice.dev/onboarding). |
| 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](https://goldprice.dev/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_fetch` so 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 `bcdiv` against troy-ounce-to-gram factors for a per-gram retail view

## Questions

### How often does the price update?

The spot endpoint refreshes every 60 seconds (live spot data; Free/keyless delayed 15 minutes, paid live). The 60-second TTL above matches that cadence, repeated spot() calls within the window return the cached array without an HTTP round-trip.

### Will this fit the free tier with auto-refresh?

It depends on your traffic. A page that calls the API on every uncached request can exceed the 5,000/month free tier quickly under load; share the cache via APCu so one fetch serves many requests. Low-traffic sites calling a few times an hour stay well inside the free tier. For continuous high-volume use, see /pricing for paid plans.

### Can I use this commercially?

Commercial use is allowed on every plan. Paid plans need no credit link; Free requires a visible link to goldprice.dev near the prices.

### Why BCMath instead of float?

PHP floats are IEEE-754 doubles: 0.1 + 0.2 is 0.30000000000000004, and errors accumulate across many operations. Gold prices carry 2 decimal places, so summing thousands of values in float drifts by basis points. BCMath works on the decimal strings directly with a fixed scale, so totals stay exact.

### Do I really not need Composer or Guzzle?

Correct, curl and json are bundled with PHP 8, so this client has zero install step beyond the API key. If you already run Guzzle, swap curl_* for a Guzzle client with a retry middleware; the request shape (a GET with the X-API-Key header) is identical.

### What metals are supported?

Gold (XAU), silver (XAG), copper (HG), platinum and palladium are not offered on any tier. Substitute the metal code in the symbol, e.g. $client->spot("XAG-USD-SPOT").

### Can I have Claude write this for me?

Yes. Open Claude Desktop with the goldprice.dev MCP server installed and ask: Build a PHP 8 client for the goldprice.dev /v1/spot endpoint. Use native cURL (no Composer), a 60-second per-symbol static cache, retry-on-429 with exponential backoff, and keep prices as strings for BCMath. Read the API key from GOLDPRICE_API_KEY. The MCP server gives Claude the live schema, so generated code uses correct field names on the first try.

## Keep reading

- [Python logo How to get live gold prices in Python](https://goldprice.dev/tutorials/python)
- [Go logo How to get live gold prices in Go](https://goldprice.dev/tutorials/go)
- [Zapier logo How to get live gold prices in Zapier](https://goldprice.dev/tutorials/zapier)

Source: https://goldprice.dev/tutorials/php
