Slim - How to send response with “Content-Type: application/json” header?

混江龙づ霸主 提交于 2019-12-03 04:26:52

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.

conrad10781

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.

For V3, the simplest method as per the Slim docs is:

$data = array('name' => 'Rob', 'age' => 40);
return $response->withJson($data, 201);

This automatically sets the Content-Type to application/json;charset=utf-8 and lets you set a HTTP status code too (defaults to 200 if omitted).

You can also use:

$response = $response->withHeader('Content-Type', 'application/json');
$response->write(json_encode($student));
return $response;

because withHeader return new response object. That way you have more then one write and code between.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!