1. <?php
  2. /**
  3. * Safely decode a JSON string, handling potential errors gracefully.
  4. *
  5. * @param string $jsonString The JSON string to decode.
  6. * @return mixed The decoded JSON object, or null on failure.
  7. */
  8. function safeJsonDecode(string $jsonString)
  9. {
  10. try {
  11. // Attempt to decode the JSON string.
  12. $jsonObject = json_decode($jsonString, true); // Use true for associative arrays
  13. return $jsonObject;
  14. } catch (JsonException $e) {
  15. // Handle JSON decoding errors.
  16. error_log("JSON decoding error: " . $e->getMessage()); // Log the error
  17. return null; // Return null on failure.
  18. }
  19. }
  20. // Example Usage (for testing):
  21. /*
  22. $json = '{"name": "John", "age": 30}';
  23. $data = safeJsonDecode($json);
  24. if ($data !== null) {
  25. print_r($data);
  26. } else {
  27. echo "Failed to decode JSON.\n";
  28. }
  29. $invalidJson = '{"name": "John", "age": 30'; //missing closing brace
  30. $data = safeJsonDecode($invalidJson);
  31. if ($data !== null) {
  32. print_r($data);
  33. } else {
  34. echo "Failed to decode JSON.\n";
  35. }
  36. */
  37. ?>

Add your comment