1. <?php
  2. /**
  3. * Splits a JSON response into smaller chunks for debugging, with fallback logic.
  4. *
  5. * @param string $json_string The JSON string to split.
  6. * @param int $chunk_size The desired size of each chunk (in characters).
  7. * @param string $fallback_data Optional fallback data to use if JSON parsing fails.
  8. * @return array|string An array of chunks if successful, or the fallback data if parsing fails.
  9. */
  10. function splitJsonForDebugging(string $json_string, int $chunk_size, string $fallback_data = "JSON parsing failed"): array|string
  11. {
  12. // Attempt to decode the JSON string
  13. $data = json_decode($json_string, true);
  14. // Check for JSON decoding errors
  15. if (json_last_error() !== JSON_ERROR_NONE) {
  16. return $fallback_data; // Return fallback data on error
  17. }
  18. $data_length = strlen(json_encode($data)); // Get the length of the encoded data
  19. $chunks = [];
  20. $start = 0;
  21. // Split the data into chunks
  22. while ($start < $data_length) {
  23. $end = min($start + $chunk_size, $data_length);
  24. $chunks[] = substr($json_string, $start, $end - $start);
  25. $start = $end;
  26. }
  27. return $chunks;
  28. }
  29. // Example usage:
  30. /*
  31. $json = '{
  32. "name": "John Doe",
  33. "age": 30,
  34. "city": "New York",
  35. "details": {
  36. "occupation": "Software Engineer",
  37. "skills": ["PHP", "JavaScript", "MySQL"]
  38. }
  39. }';
  40. $chunk_size = 100;
  41. $chunks = splitJsonForDebugging($json, $chunk_size);
  42. if (is_array($chunks)) {
  43. foreach ($chunks as $i => $chunk) {
  44. echo "Chunk " . ($i + 1) . ": " . $chunk . "<br>";
  45. }
  46. } else {
  47. echo $chunks; // Output the fallback data
  48. }
  49. */
  50. ?>

Add your comment