1. <?php
  2. /**
  3. * Prepares environment for JSON responses with limited memory.
  4. *
  5. * This function aims to create JSON responses efficiently,
  6. * minimizing memory usage, suitable for one-off scripts.
  7. *
  8. * @param array $data The data to be encoded as JSON.
  9. * @param int $prettyPrint Optional. If true, formats JSON for readability.
  10. * @return string JSON string.
  11. */
  12. function prepareJsonResponse(array $data, bool $prettyPrint = false): string
  13. {
  14. // Use json_encode with resource to avoid buffering large strings in memory.
  15. $jsonString = json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
  16. if ($prettyPrint) {
  17. $jsonString = json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
  18. }
  19. if ($jsonString === false) {
  20. // Handle JSON encoding errors gracefully.
  21. error_log("JSON encoding error: " . json_last_error_msg());
  22. return json_encode(['error' => 'Failed to encode to JSON'], JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
  23. }
  24. return $jsonString;
  25. }
  26. //Example usage
  27. /*
  28. $data = ['name' => 'John Doe', 'age' => 30, 'city' => 'New York'];
  29. $json = prepareJsonResponse($data, true);
  30. echo $json;
  31. */
  32. ?>

Add your comment