<?php
/**
* Prepares environment for JSON responses with limited memory.
*
* This function aims to create JSON responses efficiently,
* minimizing memory usage, suitable for one-off scripts.
*
* @param array $data The data to be encoded as JSON.
* @param int $prettyPrint Optional. If true, formats JSON for readability.
* @return string JSON string.
*/
function prepareJsonResponse(array $data, bool $prettyPrint = false): string
{
// Use json_encode with resource to avoid buffering large strings in memory.
$jsonString = json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
if ($prettyPrint) {
$jsonString = json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
}
if ($jsonString === false) {
// Handle JSON encoding errors gracefully.
error_log("JSON encoding error: " . json_last_error_msg());
return json_encode(['error' => 'Failed to encode to JSON'], JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
}
return $jsonString;
}
//Example usage
/*
$data = ['name' => 'John Doe', 'age' => 30, 'city' => 'New York'];
$json = prepareJsonResponse($data, true);
echo $json;
*/
?>
Add your comment