1. <?php
  2. /**
  3. * Imports data from a JSON file and handles errors gracefully.
  4. *
  5. * @param string $jsonFilePath The path to the JSON file.
  6. * @return array|null An array containing the parsed JSON data, or null on failure.
  7. */
  8. function importJsonData(string $jsonFilePath): ?array
  9. {
  10. try {
  11. // Attempt to decode the JSON file
  12. $jsonData = file_get_contents($jsonFilePath);
  13. if ($jsonData === false) {
  14. // Handle file read error
  15. error_log("Error: Could not read JSON file at $jsonFilePath");
  16. return null;
  17. }
  18. $data = json_decode($jsonData, true); // Decode to associative array
  19. if (json_last_error() !== JSON_ERROR_NONE) {
  20. // Handle JSON decoding error
  21. error_log("Error: JSON decoding error: " . json_last_error_msg());
  22. return null;
  23. }
  24. return $data;
  25. } catch (Exception $e) {
  26. //Catch any other exceptions
  27. error_log("An unexpected error occurred: " . $e->getMessage());
  28. return null;
  29. }
  30. }
  31. //Example usage
  32. //$data = importJsonData('data.json');
  33. //if ($data !== null) {
  34. // print_r($data);
  35. //} else {
  36. // echo "Failed to import JSON data.\n";
  37. //}
  38. ?>

Add your comment