Slim - How to send response with "Content-Type: application/json" header?
So, instead of this:
if($student) { $response->withHeader('Content-Type', 'application/json'); $response->write(json_encode($student)); return $response; } else { throw new PDOException('No records found');}
Do like this:
if($student) { return $response->withStatus(200) ->withHeader('Content-Type', 'application/json') ->write(json_encode($student));} else { throw new PDOException('No records found');}
And all is well and good.
For V3, withJson()
is available.
So you can do something like:
return $response->withStatus(200) ->withJson(array($request->getAttribute("route") ->getArgument("someParameter")));
Note: Make sure you return the $response
because if you forget, the response will still come out but it will not be application/json
.