Large output with Slim 3

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?

Is your question: I want to output JSON in a streaming way?
(which is the same answer form html)

Yes. (but not from an I/O stream, this is generated data)

Look at this, and see if it is a fit:

Not really a fit, as i would have to implement a stream interface for the generated data.

This would be about 20x the code to write and maintain than I was hoping for; a little too much for my slim 2->3 upgrade.