1. <?php
  2. /**
  3. * Splits a JSON string into chunks with a timeout.
  4. *
  5. * @param string $jsonString The JSON string to split.
  6. * @param int $chunkSize The maximum size of each chunk in bytes.
  7. * @param int $timeout The timeout in seconds.
  8. * @return array An array of JSON chunks, or an empty array on failure.
  9. */
  10. function splitJsonWithTimeout(string $jsonString, int $chunkSize, int $timeout): array
  11. {
  12. $chunks = [];
  13. $length = strlen($jsonString);
  14. $start = 0;
  15. while ($start < $length) {
  16. $end = min($start + $chunkSize, $length);
  17. // Check for timeout
  18. if (intval(microtime(true)) - $_SERVER['REQUEST_TIME'] > $timeout) {
  19. error_log("Timeout reached during JSON splitting.");
  20. return []; // Return empty array on timeout
  21. }
  22. $chunk = substr($jsonString, $start, $end - $start);
  23. $chunks[] = $chunk;
  24. $start = $end;
  25. }
  26. return $chunks;
  27. }
  28. //Example Usage:
  29. /*
  30. $json = '{"name": "John Doe", "age": 30, "city": "New York"}';
  31. $chunkSize = 1024; // 1KB
  32. $timeout = 5; // 5 seconds
  33. $chunks = splitJsonWithTimeout($json, $chunkSize, $timeout);
  34. foreach ($chunks as $i => $chunk) {
  35. echo "Chunk " . ($i + 1) . ": " . $chunk . "\n";
  36. }
  37. */
  38. ?>

Add your comment