Bulk and spreadsheets › A month of results into CSV
A month of results into CSV
Every settled race in Great Britain last month with its winner, page by page, into one CSV file you can open in any spreadsheet.
<?php
// A month of results into CSV: page by page with the cursor
$from = date("Y-m-01", strtotime("first day of last month"));
$to = date("Y-m-t", strtotime("last day of last month"));
$ctx = stream_context_create(["http" => ["header" => "X-API-Key: " . getenv("AHR_KEY"), "ignore_errors" => true]]);
$out = fopen("results.csv", "w");
fputcsv($out, ["date", "time", "course", "name", "winner", "sp", "trainer"]);
$cursor = "";
do {
$q = http_build_query(["region" => "GB", "date_from" => $from, "date_to" => $to, "result_available" => 1,
"include" => "winner", "limit" => 200, "cursor" => $cursor]);
$body = json_decode(file_get_contents("https://api.apihorseracing.com/v1/races/search?" . $q, false, $ctx), true);
foreach ($body["data"] as $r) {
$w = $r["winner"] ?? [];
fputcsv($out, [$r["date"], $r["time"], $r["course"], $r["name"], $w["horse"] ?? "", $w["sp"] ?? "", $w["trainer"] ?? ""]);
}
$cursor = $body["meta"]["next_cursor"] ?? "";
} while (!empty($body["meta"]["has_more"]));
fclose($out);
What the reply holds
- data[]
- One row per race.
- winner
- The winner, its SP and trainer.
- meta.has_more
- Whether there is another page.
- meta.next_cursor
- Pass it as cursor for the next page.
When it says no
401no_key The key is missing or mistyped. Every sample reads it from AHR_KEY.403plan_needed Your plan does not reach this. The reply names the plan that does.429rate_limited Too fast. Wait the seconds in Retry-After, then try again.