Hi,
I’m trying to migrate from Slim 2->3.
Previously I was collecting a number of database rows in an array, and output that array as JSON via a function that echo:ed the (now JSON-encoded) rows out one by one, since the memory consumption more than doubled if I stored the entire JSON-encoded data in a variable:
(code edited for brevity)
Slim 2 (working)
$app->get('/stuff/:arg', function($arg) use($app) {
get_stuff($app, $arg);
});
function get_stuff($app, $arg)
....
$app->response->setStatus(200);
$app->response->headers->set('Content-Type', 'application/json');
echo_large_json_encode($data);
return;
}
function echo_large_json_encode(&$array) {
$array_size = sizeof($array);
if($array_size == 0) return;
echo "[";
for($i = 0; $i < $array_size; $i++) {
echo json_encode($array[$i]);
if($i < $array_size - 1) echo ",\n";
}
echo "]";
}
With Slim 3, I’m calling stuff a bit differently
$app->get('/stuff/{arg}', function($request, $response, $args) {
return get_stuff($request, $response, $args);
});
function get_stuff($request, $response, $args) {
...
return $response->withStatus(200)
->withHeader('Content-Type', 'application/json')
->write(json_encode($data));
Here, I get no chance of iterating over $data…
How can I echo directly to browser output, so to speak?