<?php
/**
* Paginate HTTP response results with retry and fixed intervals.
*
* @param string $url The URL to fetch data from.
* @param int $pageSize The number of results per page.
* @param int $retryInterval The interval between retries in seconds.
* @return array An array containing the paginated results, total count, and URL.
* Returns an empty array on error.
*/
function paginateHttp(string $url, int $pageSize, int $retryInterval): array
{
$allResults = [];
$currentPage = 1;
$totalCount = 0;
do {
try {
$response = file_get_contents($url); // Fetch the data
if ($response === false) {
error_log("Error fetching URL: $url");
return []; // Return empty array on failure
}
$data = json_decode($response, true); // Decode JSON
if ($data === null) {
error_log("Error decoding JSON from URL: $url");
return []; // Return empty array on failure
}
$results = $data['results'] ?? []; // Assuming 'results' key contains the items
$totalCount = count($results);
$allResults = array_merge($allResults, $results);
if (empty($results)) {
break; // No more results
}
$url = $data['next'] ?? null; // Assuming 'next' key contains the URL for the next page
if ($url === null) {
break; // No next page
}
$currentPage++;
usleep($retryInterval * 1000000); // Wait before retrying
} catch (Exception $e) {
error_log("Error during pagination: " . $e->getMessage());
return []; // Return empty array on error
}
} while ($url !== null);
$totalPages = ceil($totalCount / $pageSize);
return [
'results' => array_slice($allResults, ($currentPage - 1) * $pageSize, $pageSize),
'totalCount' => $totalCount,
'pageSize' => $pageSize,
'totalPages' => $totalPages,
'url' => $url
];
}
?>
Add your comment