1. <?php
  2. /**
  3. * Imports data from a JSON file with retry logic.
  4. *
  5. * @param string $jsonFilePath The path to the JSON file.
  6. * @param callable $dataCallback A callback function that processes each JSON object. Receives the object as an argument.
  7. * @param int $maxRetries The maximum number of retry attempts.
  8. * @param int $retryDelay The delay in seconds between retries.
  9. * @return bool True on success, false on failure.
  10. */
  11. function importJsonData(string $jsonFilePath, callable $dataCallback, int $maxRetries = 3, int $retryDelay = 5): bool
  12. {
  13. $totalRetries = 0;
  14. while ($totalRetries < $maxRetries) {
  15. try {
  16. // Read the JSON file
  17. $jsonData = file_get_contents($jsonFilePath);
  18. if ($jsonData === false) {
  19. error_log("Error reading JSON file: " . $jsonFilePath);
  20. $totalRetries++;
  21. if ($totalRetries < $maxRetries) {
  22. sleep($retryDelay);
  23. }
  24. continue; // Retry
  25. }
  26. // Decode the JSON data
  27. $data = json_decode($jsonData, true);
  28. if ($data === null) {
  29. $error = json_last_error_msg();
  30. error_log("Error decoding JSON: " . $error);
  31. $totalRetries++;
  32. if ($totalRetries < $maxRetries) {
  33. sleep($retryDelay);
  34. }
  35. continue; // Retry
  36. }
  37. // Process each JSON object
  38. if (is_array($data)) {
  39. foreach ($data as $item) {
  40. $dataCallback($item); // Call the provided callback function
  41. }
  42. } else {
  43. $dataCallback($data); // If not an array, treat it as a single object.
  44. }
  45. return true; // Success
  46. } catch (Exception $e) {
  47. error_log("An unexpected error occurred: " . $e->getMessage());
  48. $totalRetries++;
  49. if ($totalRetries < $maxRetries) {
  50. sleep($retryDelay);
  51. }
  52. continue; // Retry
  53. }
  54. }
  55. error_log("Import failed after " . $maxRetries . " retries.");
  56. return false; // Failure
  57. }
  58. /**
  59. * Example usage (replace with your actual data processing logic)
  60. *
  61. * @param array $item A single JSON object.
  62. */
  63. function processJsonItem(array $item): void
  64. {
  65. // Your data processing logic here.
  66. echo "Processing item: " . json_encode($item) . "\n";
  67. }
  68. // Example call
  69. //$success = importJsonData('data.json', 'processJsonItem', 5, 2);
  70. ?>

Add your comment