How to Get Oil Prices in PHP (Complete Tutorial)
Fetch Brent, WTI, and diesel prices in PHP using the official OilPriceAPI SDK — one Composer package, zero dependencies, works on shared hosting and WordPress. Then put it in production with a cron script that logs source-timestamped prices to CSV. Every example on this page was run against the live API with PHP 8.5.
Why PHP for Price Data?
PHP still runs most of the web — WordPress sites quoting fuel surcharges, Laravel dashboards for logistics teams, plain scripts on shared hosting. The official OilPriceAPI PHP SDK (v2 on Packagist) is built for exactly that environment: one class, strict types, immutable DTOs, and zero dependencies beyond ext-curl and ext-json — no Guzzle version conflicts with your host's packages.
What You'll Build
- ✓ Fetch the latest Brent price in three lines
- ✓ Try live prices with no API key (demo mode)
- ✓ Pull a week of history and handle typed exceptions
- ✓ A cron-invoked script logging Brent, WTI, and diesel to CSV every 15 minutes
Requirements: PHP 8.1+ (examples verified on PHP 8.5) and Composer — or skip Composer entirely with the plain cURL version below.
Step 1: Install via Composer
composer require oilpriceapi/oilpriceapi
Get Your API Key
Sign up at oilpriceapi.com — 7-day free trial, then a free tier of 200 requests per month. No credit card required. Export it as an environment variable instead of hardcoding it:
export OILPRICEAPI_KEY="your_api_key_here"
Step 2: Quickstart
<?php
require __DIR__ . '/vendor/autoload.php';
use OilPriceAPI\Client;
$client = new Client(getenv('OILPRICEAPI_KEY') ?: null);
$brent = $client->latest('BRENT_CRUDE_USD');
printf(
"%s: %s %.2f per %s (as of %s)\n",
$brent->code,
$brent->currency,
$brent->price,
$brent->unit,
$brent->updatedAt?->format('Y-m-d H:i T') ?? 'n/a',
);Verified output: BRENT_CRUDE_USD: USD 71.73 per barrel (as of 2026-07-05 22:18 Z) — note the response tells you exactly when the quote was sourced.
latest() returns an immutable Price DTO with code, price, currency, updatedAt, and change24h. Called without a code, it returns every commodity on your plan.
Try It with No API Key
Demo mode serves live prices for a limited commodity set — no signup:
$client = new \OilPriceAPI\Client(); // no key
foreach ($client->demoPrices() as $price) {
printf("%s: %s %.2f\n", $price->code, $price->currency, $price->price);
}Verified: returned nine live demo commodities, e.g. BRENT_CRUDE_USD: USD 71.73, DIESEL_USD: USD 3.25.
No Composer? Plain cURL
On a locked-down host, the whole integration is a dozen lines of built-in cURL (this is the snippet from the SDK's own README):
<?php
// Latest Brent price from OilPriceAPI - plain PHP, no libraries needed.
$apiKey = getenv('OILPRICEAPI_KEY') ?: 'your_api_key_here';
$ch = curl_init('https://api.oilpriceapi.com/v1/prices/latest?by_code=BRENT_CRUDE_USD');
curl_setopt_array($ch, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 10,
CURLOPT_HTTPHEADER => [
'Authorization: Token ' . $apiKey,
'Accept: application/json',
],
]);
$response = curl_exec($ch);
$json = json_decode($response, true);
echo $json['data']['price'] ?? 'No price returned';Need this data in your app?
GET /v1/prices/latest?by_code=BRENT_CRUDE_USD → timestamped JSONHistorical Prices & Error Handling
Fixed lookback windows are one method call each:
$day = $client->pastDay('BRENT_CRUDE_USD'); // last 24 hours
$week = $client->pastWeek('BRENT_CRUDE_USD');
$month = $client->pastMonth('BRENT_CRUDE_USD');
$year = $client->pastYear('BRENT_CRUDE_USD');
foreach ($week as $price) {
echo $price->updatedAt?->format('Y-m-d H:i'), ' -> ', $price->price, PHP_EOL;
}All SDK exceptions extend ApiException, with typed subclasses for the two failures you'll actually branch on:
use OilPriceAPI\Exception\ApiException;
use OilPriceAPI\Exception\AuthenticationException;
use OilPriceAPI\Exception\RateLimitException;
try {
$price = $client->latest('BRENT_CRUDE_USD');
} catch (AuthenticationException $e) {
// 401 or missing key - message includes the signup URL
} catch (RateLimitException $e) {
// 429 after retries - $e->retryAfter (seconds), $e->limit
} catch (ApiException $e) {
// everything else - $e->statusCode, $e->responseBody
}Retries are built in: 429/5xx responses are retried automatically (default 3 attempts) with exponential backoff plus jitter, honoring Retry-After exactly. For endpoints the SDK doesn't wrap yet, the $client->raw()->get(...) escape hatch reaches anything.
Production: A Cron-Driven Price Logger
Echoing one price is a demo. The production ending is a script cron runs for you — every 15 minutes it appends Brent, WTI, and diesel to a CSV with both your polled-at time and the API's own source timestamp, holds a file lock against overlapping runs, and one failing commodity doesn't kill the rest:
<?php
declare(strict_types=1);
// fetch_prices.php — run from cron, appends one row per commodity to CSV.
require __DIR__ . '/vendor/autoload.php';
use OilPriceAPI\Client;
use OilPriceAPI\Exception\ApiException;
$codes = ['BRENT_CRUDE_USD', 'WTI_USD', 'DIESEL_USD'];
$csvPath = __DIR__ . '/prices.csv';
$client = new Client(getenv('OILPRICEAPI_KEY') ?: null);
$isNew = !file_exists($csvPath);
$fh = fopen($csvPath, 'ab');
if ($fh === false) {
fwrite(STDERR, "cannot open {$csvPath}\n");
exit(1);
}
flock($fh, LOCK_EX);
if ($isNew) {
fputcsv($fh, ['polled_at', 'code', 'price', 'currency', 'unit', 'source_updated_at'], escape: '\\');
}
$failures = 0;
foreach ($codes as $code) {
try {
$p = $client->latest($code);
fputcsv($fh, [
gmdate('c'),
$p->code,
number_format($p->price, 2, '.', ''),
$p->currency,
$p->unit,
$p->updatedAt?->format('c') ?? '',
], escape: '\\');
printf("%s $%.2f (source ts %s)\n", $p->code, $p->price, $p->updatedAt?->format('c') ?? 'n/a');
} catch (ApiException $e) {
// One bad commodity shouldn't kill the whole cron run.
fwrite(STDERR, "{$code}: {$e->getMessage()}\n");
$failures++;
}
}
flock($fh, LOCK_UN);
fclose($fh);
exit($failures === count($codes) ? 1 : 0);Verified: one live run produced:
polled_at,code,price,currency,unit,source_updated_at 2026-07-05T22:19:46+00:00,BRENT_CRUDE_USD,71.73,USD,barrel,2026-07-05T22:18:20+00:00 2026-07-05T22:19:46+00:00,WTI_USD,68.48,USD,barrel,2026-07-05T22:07:20+00:00 2026-07-05T22:19:47+00:00,DIESEL_USD,3.25,USD,gallon,2026-07-03T16:25:13+00:00
Notice the diesel source timestamp is two days older than Brent's — this run happened on a weekend, and the Gulf Coast diesel series updates on its own schedule. That's exactly why you store the source timestamp instead of assuming everything is fresh.
Schedule It
# crontab -e — every 15 minutes, weekdays */15 * * * 1-5 OILPRICEAPI_KEY=your_api_key_here /usr/bin/php /var/app/fetch_prices.php >> /var/log/oilprices.log 2>&1
Sizing the cadence: three commodities every 15 minutes on weekdays is ~6,200 requests/month — inside the Developer plan's 10,000-request monthly limit — while the free tier's 200 requests/month comfortably covers a daily fetch of all three. Polling faster than the source updates just re-reads the same quote.
Prefer a database? Swap the fputcsv calls for a PDO INSERT — the fetch loop and error handling stay identical. On WordPress, run the same fetch from a WP-Cron hook and cache the result in a transient, or skip code entirely with the official WordPress plugin.
Frequently Asked Questions
Q: How do I get oil prices in PHP?
A: Run composer require oilpriceapi/oilpriceapi, create a client with new \OilPriceAPI\Client($apiKey), and call $client->latest("BRENT_CRUDE_USD"). No Composer? A dozen lines of plain cURL work too.
Q: Does it work on shared hosting and WordPress?
A: Yes. The SDK needs only ext-curl and ext-json on PHP 8.1+, so it drops into shared hosting, themes, and plugins without dependency conflicts. There's also an official WordPress plugin for no-code widgets.
Q: Is there a free PHP oil price API?
A: Yes. Demo mode ($client->demoPrices()) returns live prices for a limited commodity set without any key. A free account adds a 7-day trial, then a free tier of 200 requests per month.
Q: How do I fetch prices on a schedule?
A: Write a small CLI script that appends prices to CSV or a database and add it to crontab — the production section above has a verified script and crontab line. Store the API's source timestamp with every row.
Q: How fresh is the price data?
A: Every response carries source timestamps. Spot prices like Brent and WTI update at market cadence during trading hours; some series, like Gulf Coast diesel, update daily or pause over weekends — the timestamp always tells you exactly how old a quote is.
Put It on the Crontab
Ready to Get Started?
Install the SDK and get your free API key — 7-day trial, then 200 requests/month free. No credit card required.
composer require oilpriceapi/oilpriceapi
110+ commodities • Zero dependencies • PHP 8.1+ • Typed exceptions