请求对象有一个方法可以将数组转换为JSON,同时设置header。 See documentation here
$app->get('/joinable', function ($request, $response, $args) {
return $response->withJson(getJoinable());
});
除了getJoinable()需要返回一个Array,因为withJson()会帮你转成json。
现在,如果你坚持自己设置标题,see the documentation here
代码如下所示
$app->get('/joinable', function ($request, $response, $args) {
$body = $this->getBody();
$body->rewind(); // ensure your JSON is the only thing in the body
$body->write(getJoinable());
return $response->withHeader('Content-Type', 'application/json;charset=utf-8');
});
如果您确定此时正文为空,您可以保存一个步骤,只需使用 Response 对象中的 write() 方法即可。
$app->get('/joinable', function ($request, $response, $args) {
$response->write(getJoinable());
$response = $response->withHeader('Content-Type', 'application/json;charset=utf-8');
return $response;
});
甚至更短的符号
$app->get('/joinable', function ($request, $response, $args) {
return $response->write(getJoinable())
->withHeader('Content-Type', 'application/json;charset=utf-8');
});
使用 PHP 5.4+,您可能还需要漂亮的 json 打印(不建议用于较大的有效负载,因为它会增加大约 10-25% 的传输字节大小):
$app->get('/joinable', function ($request, $response, $args) {
return $response->write(json_encode(getJoinable(), JSON_PRETTY_PRINT))
->withHeader('Content-Type', 'application/json;charset=utf-8');
});