<?php
/**
* Splits a JSON response into smaller chunks for debugging, with fallback logic.
*
* @param string $json_string The JSON string to split.
* @param int $chunk_size The desired size of each chunk (in characters).
* @param string $fallback_data Optional fallback data to use if JSON parsing fails.
* @return array|string An array of chunks if successful, or the fallback data if parsing fails.
*/
function splitJsonForDebugging(string $json_string, int $chunk_size, string $fallback_data = "JSON parsing failed"): array|string
{
// Attempt to decode the JSON string
$data = json_decode($json_string, true);
// Check for JSON decoding errors
if (json_last_error() !== JSON_ERROR_NONE) {
return $fallback_data; // Return fallback data on error
}
$data_length = strlen(json_encode($data)); // Get the length of the encoded data
$chunks = [];
$start = 0;
// Split the data into chunks
while ($start < $data_length) {
$end = min($start + $chunk_size, $data_length);
$chunks[] = substr($json_string, $start, $end - $start);
$start = $end;
}
return $chunks;
}
// Example usage:
/*
$json = '{
"name": "John Doe",
"age": 30,
"city": "New York",
"details": {
"occupation": "Software Engineer",
"skills": ["PHP", "JavaScript", "MySQL"]
}
}';
$chunk_size = 100;
$chunks = splitJsonForDebugging($json, $chunk_size);
if (is_array($chunks)) {
foreach ($chunks as $i => $chunk) {
echo "Chunk " . ($i + 1) . ": " . $chunk . "<br>";
}
} else {
echo $chunks; // Output the fallback data
}
*/
?>
Add your comment