How to Build an NHL Website in PHP with the SportAPI Hockey API
You are going to build a small NHL website in PHP with the SportAPI hockey API: league standings split by division, a daily scoreboard with live scores and a game page with the score by period and every goal and penalty. It runs on any PHP host, needs no framework and no database, and keeps the API key on the server.
We built a full version of the same idea at nhl.sportapi.ai. It has team pages, rosters, stat leaders, box scores and play-by-play. At the end of this guide you will see how it grows from the example.
What you need
- PHP 8.1 or newer with the curl extension. Shared hosting is fine.
- A free SportAPI key. Create an account and generate a key in your dashboard. The free plan gives 1,000 requests a day, which is enough for this site.
- About 30 minutes.
The example has five files: api.php with the shared code, three pages and a stylesheet. You can download all of them as a zip.
How the site gets its data
Every page calls the API through one function. The function keeps each answer in a cache folder as a JSON file and only asks the API again when the copy is older than the time you give it. Standings change after games, so they are refreshed every 15 minutes. Today's scores are refreshed every minute while a game is on and every 10 minutes otherwise. Visitors never wait for the API on a cached page, and a hundred visitors cost the same number of requests as one.
The key is read from the SPORTAPI_KEY environment variable. Set it in your hosting panel, in the web server config or with SetEnv SPORTAPI_KEY your_key in .htaccess on Apache. Never put it in JavaScript: anything sent to the browser can be copied.
One function for every request
<?php
// One function for every request to the SportAPI hockey API, with a file cache.
// The key comes from the SPORTAPI_KEY environment variable and never reaches the browser.
const API_BASE = 'https://sportapi.ai/api/hockey';
const CACHE_DIR = __DIR__ . '/cache';
date_default_timezone_set('America/New_York'); // NHL dates and times in Eastern Time
function api(string $path, int $ttl): ?array
{
$file = CACHE_DIR . '/' . md5($path) . '.json';
if (is_file($file) && time() - filemtime($file) < $ttl) {
return json_decode(file_get_contents($file), true);
}
$ch = curl_init(API_BASE . $path);
curl_setopt_array($ch, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => ['X-API-Key: ' . getenv('SPORTAPI_KEY')],
CURLOPT_TIMEOUT => 20,
]);
$body = curl_exec($ch);
$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
$json = $code === 200 ? json_decode($body, true) : null;
if (empty($json['success'])) {
// API down or limit reached: show the last good copy instead of an error
return is_file($file) ? json_decode(file_get_contents($file), true) : null;
}
if (!is_dir(CACHE_DIR)) mkdir(CACHE_DIR, 0755, true);
file_put_contents($file, $body, LOCK_EX);
return $json;
}
function e(?string $s): string
{
return htmlspecialchars((string) $s, ENT_QUOTES, 'UTF-8');
}
// FT, OT or SO for finished games, the period for live ones, the puck-drop time otherwise
function game_status(array $g): string
{
if (in_array($g['status'], ['FT', 'AOT', 'AP'], true)) {
return ['REG' => 'Final', 'OT' => 'Final/OT', 'SO' => 'Final/SO'][$g['decision']] ?? 'Final';
}
if ($g['live']) {
return $g['status'] === 'BT' ? 'Intermission' : $g['status'] . ($g['clock'] ? ' ' . $g['clock'] : '');
}
return date('g:i A', strtotime($g['start'])) . ' ET';
}
function page_start(string $title): void
{
echo '<!doctype html><html lang="en"><head><meta charset="utf-8">'
. '<meta name="viewport" content="width=device-width, initial-scale=1">'
. '<title>' . e($title) . '</title><link rel="stylesheet" href="style.css"></head><body>'
. '<nav><a href="index.php">Standings</a> <a href="scores.php">Scores</a></nav><main>';
}
function page_end(): void
{
echo '</main><footer>Data: <a href="https://sportapi.ai/hockey-api">SportAPI hockey API</a></footer></body></html>';
}Three details matter here:
- Last good copy. If the API is down or the daily limit is reached,
api()returns the old file instead of nothing, so the page still works with slightly older data. - Eastern Time. NHL schedules use Eastern Time, so the script sets
America/New_Yorkonce. A game that starts at 7 PM in New York is listed under the right day, not the next day in UTC. - Status in words. The API returns
FTfor finished games anddecisiontells you how they ended:REG,OTorSO. Live games havelive: true, the period instatus(P1,P2,P3,OT) andBTduring an intermission.
Standings by division
The standings endpoint returns the whole league in one table, sorted by points. Conferences and divisions come from /leagues/nhl, which lists every team with its conference and division. That list changes once a season, so it is cached for a day.
<?php
// NHL standings by division: the table comes from /standings, divisions from /leagues/nhl
require __DIR__ . '/api.php';
$league = api('/leagues/nhl', 86400); // teams with conference and division, once a day
$standings = api('/standings/nhl', 900); // the table, every 15 minutes
$division = [];
foreach ($league['data']['teams'] as $t) {
$division[$t['id']] = $t['conference'] . ' · ' . $t['division'];
}
$groups = [];
foreach ($standings['data'][0]['table'] as $row) {
$groups[$division[$row['team']['id']]][] = $row; // rows stay in league order
}
ksort($groups);
page_start('NHL standings ' . $standings['season']);
echo '<h1>NHL standings ' . e($standings['season']) . '</h1>';
foreach ($groups as $name => $rows) {
echo '<h2>' . e($name) . '</h2><table><tr><th></th><th class="team">Team</th>'
. '<th>GP</th><th>W</th><th>L</th><th>OTL</th><th>PTS</th><th>P%</th>'
. '<th>GF</th><th>GA</th><th>DIFF</th><th>L10</th><th>STRK</th></tr>';
foreach ($rows as $i => $r) { // ot_lost already includes shootout losses: GP = W + L + OTL
printf(
'<tr><td>%d</td><td class="team">%s</td><td>%d</td><td>%d</td><td>%d</td><td>%d</td>'
. '<td><b>%d</b></td><td>%s</td><td>%d</td><td>%d</td><td>%+d</td><td>%s</td><td>%s</td></tr>',
$i + 1, e($r['team']['name']), $r['played'], $r['won'], $r['lost'], $r['ot_lost'], $r['points'],
ltrim(number_format($r['point_pct'], 3), '0'), $r['goals_for'], $r['goals_against'],
$r['goal_diff'], e($r['last10']), e($r['streak'])
);
}
echo '</table>';
}
page_end();
The columns follow NHL conventions. ot_lost already includes shootout losses, so games played always equal wins plus losses plus overtime losses. The API also returns reg_wins and row_wins (the first two tie-breakers), home_record, away_record and point_pct. Add them as extra columns if your readers care about tie-breakers.
Daily scoreboard with live scores
/games/date/{date} returns all games on one day. The tz parameter decides which day a game belongs to, and league=nhl leaves out the other hockey leagues.
<?php
// Scoreboard for one day: ?date=2026-11-24, today by default (Eastern Time)
require __DIR__ . '/api.php';
$date = preg_match('/^\d{4}-\d{2}-\d{2}$/', $_GET['date'] ?? '') ? $_GET['date'] : date('Y-m-d');
$path = "/games/date/$date?league=nhl&tz=America/New_York";
$games = api($path, 600); // quiet day: every 10 minutes
if (array_filter($games['data'], fn($g) => $g['live'])) {
$games = api($path, 60); // a game is on: every minute
}
page_start("NHL scores $date");
$prev = date('Y-m-d', strtotime("$date -1 day"));
$next = date('Y-m-d', strtotime("$date +1 day"));
echo '<h1>NHL scores, ' . date('l, F j', strtotime($date)) . '</h1>'
. "<p class=\"days\"><a href=\"?date=$prev\">← $prev</a> <a href=\"?date=$next\">$next →</a></p>";
if (!$games['data']) echo '<p>No NHL games on this day.</p>';
foreach ($games['data'] as $g) {
$a = $g['away'];
$h = $g['home'];
$done = $g['status'] !== 'NS';
echo '<a class="game" href="game.php?id=' . $g['id'] . '">'
. '<span class="status' . ($g['live'] ? ' live' : '') . '">' . e(game_status($g)) . '</span>'
. '<span>' . e($a['name']) . '</span><b>' . ($done ? $a['score'] : '') . '</b>'
. '<span>' . e($h['name']) . '</span><b>' . ($done ? $h['score'] : '') . '</b></a>';
}
page_end();
The page first reads the cache with a 10-minute limit. Only when one of the games is live does it ask again with a one-minute limit. That keeps quiet hours cheap and live hours fresh.
Game page: score by period and goals
/games/{id}/events returns the game itself and its goals and penalties in one request: the scorer and assists, the period, the time in seconds from the start of the period and the strength (EV for even strength, PP for power play, SH for shorthanded).
<?php
// One game: score by period and the goal and penalty log from /games/{id}/events
require __DIR__ . '/api.php';
$id = (int) ($_GET['id'] ?? 0);
$res = api("/games/$id/events", 3600);
if (!$res) { http_response_code(404); exit('Game not found'); }
if ($res['game']['live']) {
$res = api("/games/$id/events", 60); // live game: refresh every minute
}
$g = $res['game'];
$sides = ['away' => $g['away'], 'home' => $g['home']];
$abbr = [$g['away']['id'] => $g['away']['abbreviation'], $g['home']['id'] => $g['home']['abbreviation']];
page_start($g['away']['name'] . ' at ' . $g['home']['name']);
echo '<h1>' . e($g['away']['name']) . ' ' . $g['away']['score'] . ', '
. e($g['home']['name']) . ' ' . $g['home']['score'] . '</h1>'
. '<p>' . e(game_status($g)) . ' · ' . e($g['venue']) . '</p>';
// Line score: one column per period, the shootout only when there was one
$periods = max(count($g['away']['periods']), count($g['home']['periods']));
echo '<table class="line"><tr><th></th>';
for ($p = 1; $p <= $periods; $p++) echo '<th>' . ($p <= 3 ? $p : 'OT') . '</th>';
echo ($g['away']['shootout'] !== null ? '<th>SO</th>' : '') . '<th>T</th><th>SOG</th></tr>';
foreach ($sides as $t) {
echo '<tr><td class="team">' . e($t['abbreviation']) . '</td>';
for ($p = 0; $p < $periods; $p++) echo '<td>' . ($t['periods'][$p] ?? '-') . '</td>';
echo ($t['shootout'] !== null ? '<td>' . $t['shootout'] . '</td>' : '')
. '<td><b>' . $t['score'] . '</b></td><td>' . $t['sog'] . '</td></tr>';
}
echo '</table>';
// Events arrive in game order; time_sec counts from the start of the period
echo '<h2>Goals and penalties</h2><ul class="events">';
foreach ($res['data'] as $ev) {
$clock = sprintf('%d:%02d', intdiv($ev['time_sec'], 60), $ev['time_sec'] % 60);
$who = e($ev['player']['name'] ?? '');
if ($ev['type'] === 'goal') {
$help = array_map(fn($p) => e($p['name']), $ev['assists'] ?? []);
$text = "<b>Goal</b> $who" . ($help ? ' (' . implode(', ', $help) . ')' : '')
. ($ev['strength'] !== 'EV' ? ' · ' . e($ev['strength']) : '');
} else {
$text = 'Penalty ' . $who . (isset($ev['minutes']) ? ', ' . $ev['minutes'] . ' min' : '');
}
echo '<li><span>P' . $ev['period'] . ' ' . $clock . '</span> <span>' . e($abbr[$ev['team_id']] ?? '') . "</span> $text</li>";
}
echo '</ul>';
page_end();
Each team's periods array holds goals per period, with a fourth value when there was overtime. shootout is null unless the game went to a shootout. Then the line score gets an SO column, and the final score already includes the shootout winner's extra goal.
The stylesheet is in the zip. It is short and uses no frameworks, so you can replace it with your own design.
How many requests the site uses
Requests depend on time, not on visitors, because every answer is cached:
- League and divisions: 1 a day.
- Standings: up to 96 a day.
- Today's scoreboard: up to 144 a day, plus up to 54 an hour while games are on. A full NHL evening costs about 270 more.
- A game page: up to 60 an hour while that game is live, and 1 an hour after it ends.
A typical day comes to about 500 requests, well inside the free 1,000. If many visitors open live game pages at the same time, check your usage in the dashboard. The Starter plan gives 10,000 requests a day for $10 a month.
From the example to a full site
nhl.sportapi.ai is built on the same API, also in PHP, with one change in design: pages never call the API. A cron job runs every minute, decides what is due (today's scoreboard, live games, rosters, player stats) and writes JSON files. Pages only read those files. That makes every page fast, and the number of requests stays the same no matter how much traffic the site gets.

The game page on the full site adds team stats (faceoffs, power play, hits, blocked shots) from /games/{id}, the box score from /games/{id}/players and play-by-play from /games/{id}/plays. Each is one request per game.

Some ideas for your next step:
- Team pages:
/teams/{id}/gamesfor the schedule and/teams/{id}/rosterfor the roster. - Stat leaders:
/leagues/nhl/leaders?stat=points, alsogoals,assists,sv_pctandgaa. - Other leagues: the same code works for the SHL, Liiga, PWHL and NCAA. Change
nhlto the league slug. The hockey API page lists them all.
No code? Use the hockey widgets
If you only need a table or live scores on an existing site, the free hockey widgets do it without PHP: standings, games with live scores, a team schedule and stat leaders. Pick the league, match the colours and paste two lines of HTML.
Download the example
nhl-php-example.zip contains api.php, index.php, scores.php, game.php and style.css. Upload them to your host, set SPORTAPI_KEY and open index.php. The cache folder is created on the first request. The web server must be able to write to it.