Slim PHP returning JSON Slim PHP returning JSON json json

Slim PHP returning JSON


Not familiar with slim framework. looks interesting. Sounds like code keeps running after json is displayed. Maybe try exit;ing the php app after responding with your json?

$app->get('/myroute', function() use ($app) {    // all the good stuff here (getting the data from the db and all that)    $dataArray = array('id' => $id, 'somethingElse' => $somethingElse);    $response = $app->response();    $response['Content-Type'] = 'application/json';    $response->body(json_encode($dataArray));    exit();});$app->run();

Hope this helps


Try to change body() to write().

I think that this will work: $response->write(json_encode($dataArray));


Slim documentation about returning JSON mentions what you are looking for.

Again from documentations, each route callback accepts three arguments:

Reques
The first argument is a Psr\Http\Message\ServerRequestInterface object that represents the current HTTP request.
Response
The second argument is a Psr\Http\Message\ResponseInterface object that represents the current HTTP response.
Arguments
The third argument is an associative array that contains values for the current route’s named placeholders.

To quote from same page:

If you use a Closure instance as the route callback, the closure’s state is bound to the Container instance. This means you will have access to the DI container instance inside of the Closure via the $this keyword.

So you don't need to uese ($app) when defining a route callback.

Also as mentioned in documentation

Ultimately, each Slim app route MUST return a PSR 7 Response object

To conclude, this should do what you expect:

$app->get('/myroute', function($request, $response, $args) {// all the good stuff here (getting the data from the db and all that)$dataArray = array('id' => $id, 'somethingElse' => $somethingElse);return $response->withJson($dataArray);});