teelou teelou - 9 days ago 7
PHP Question

Slim Framework - how to output arrays without templates?

How can I write array outputs in Slim?

$app->get('/', function ($request, $response, $args) {
$array = ['message' => 'Hello World'];
$response->getBody()->write($array);
return $response;
});


Error:


Slim Application Error The application could not run because of the
following error:

Details

Type: RuntimeException Message: Could not write to stream File:
/var/www/slim/vendor/slim/slim/Slim/Http/Stream.php Line: 407


I just want to output arrays to the screen without any templates, nor json. Is it possible?

Answer

As you cannot echo an array you need to form a string which then can be written to the outputstream.

$response->getBody()->write(print_r($array, true));

The second parameter of print_r is that it should return the value and not print it directly.

The PHPDoc specifies that the write method only accept a string see \Slim\Http\Response