<?php
/**
* Imports data from a JSON file with retry logic.
*
* @param string $jsonFilePath The path to the JSON file.
* @param callable $dataCallback A callback function that processes each JSON object. Receives the object as an argument.
* @param int $maxRetries The maximum number of retry attempts.
* @param int $retryDelay The delay in seconds between retries.
* @return bool True on success, false on failure.
*/
function importJsonData(string $jsonFilePath, callable $dataCallback, int $maxRetries = 3, int $retryDelay = 5): bool
{
$totalRetries = 0;
while ($totalRetries < $maxRetries) {
try {
// Read the JSON file
$jsonData = file_get_contents($jsonFilePath);
if ($jsonData === false) {
error_log("Error reading JSON file: " . $jsonFilePath);
$totalRetries++;
if ($totalRetries < $maxRetries) {
sleep($retryDelay);
}
continue; // Retry
}
// Decode the JSON data
$data = json_decode($jsonData, true);
if ($data === null) {
$error = json_last_error_msg();
error_log("Error decoding JSON: " . $error);
$totalRetries++;
if ($totalRetries < $maxRetries) {
sleep($retryDelay);
}
continue; // Retry
}
// Process each JSON object
if (is_array($data)) {
foreach ($data as $item) {
$dataCallback($item); // Call the provided callback function
}
} else {
$dataCallback($data); // If not an array, treat it as a single object.
}
return true; // Success
} catch (Exception $e) {
error_log("An unexpected error occurred: " . $e->getMessage());
$totalRetries++;
if ($totalRetries < $maxRetries) {
sleep($retryDelay);
}
continue; // Retry
}
}
error_log("Import failed after " . $maxRetries . " retries.");
return false; // Failure
}
/**
* Example usage (replace with your actual data processing logic)
*
* @param array $item A single JSON object.
*/
function processJsonItem(array $item): void
{
// Your data processing logic here.
echo "Processing item: " . json_encode($item) . "\n";
}
// Example call
//$success = importJsonData('data.json', 'processJsonItem', 5, 2);
?>
Add your comment