<?php
/**
* Imports data from a JSON file and handles errors gracefully.
*
* @param string $jsonFilePath The path to the JSON file.
* @return array|null An array containing the parsed JSON data, or null on failure.
*/
function importJsonData(string $jsonFilePath): ?array
{
try {
// Attempt to decode the JSON file
$jsonData = file_get_contents($jsonFilePath);
if ($jsonData === false) {
// Handle file read error
error_log("Error: Could not read JSON file at $jsonFilePath");
return null;
}
$data = json_decode($jsonData, true); // Decode to associative array
if (json_last_error() !== JSON_ERROR_NONE) {
// Handle JSON decoding error
error_log("Error: JSON decoding error: " . json_last_error_msg());
return null;
}
return $data;
} catch (Exception $e) {
//Catch any other exceptions
error_log("An unexpected error occurred: " . $e->getMessage());
return null;
}
}
//Example usage
//$data = importJsonData('data.json');
//if ($data !== null) {
// print_r($data);
//} else {
// echo "Failed to import JSON data.\n";
//}
?>
Add your comment