PHP HTTP GET JSON with stream timeout
PHP
<?php
function get_json(string $url, int $timeoutSec = 5): array
{
$context = stream_context_create([
'http' => [
'method' => 'GET',
'timeout' => $timeoutSec,
'ignore_errors' => true,
'header' => ['Accept: application/json'],
],
]);
$body = @file_get_contents($url, false, $context);
if ($body === false) {
throw new RuntimeException('Request failed: ' . $url);
}
$data = json_decode($body, true, 512, JSON_THROW_ON_ERROR);
if (!is_array($data)) {
throw new UnexpectedValueException('Expected a JSON object or array');
}
return $data;
}