如何在Slim 3中设置JSON报头?
$app->get('/joinable', function ($request, $response, $args) {
header('Content-Type: application/json');
return getJoinable(); // Returns JSON_encoded data
});我尝试过以下几种方法
$response = $app->response(); $response['Content-Type'] = 'application/json'; $app->contentType('application/json');
发布于 2016-02-17 02:10:05
从来没有使用过Slim框架,但根据their documentation的说法,它应该是这样的:
$app->get('/joinable', function ($request, $response, $args) {
$body = $response->getBody();
$body->write('{"your_content": "here"}');
return $response->withHeader(
'Content-Type',
'application/json'
)->withBody($body);
});您尝试使用header('Content-Type: application/json');的方法可能实际有效,但由于您使用的是应用程序的框架,因此您应该遵守他们的指导原则,否则会有很多问题。此外,getJoinable()是一个全球性的呼吁,你应该真正学习一些OOP,更重要的是,遵循PSR的指导方针,因为Slim 3就是使用这些指导方针构建的。
发布于 2016-02-17 07:40:43
您可以简单地执行以下操作(请注意,我使用的是内置的json编码器助手):
return $response->withJson($dataArray)->withHeader('Content-Type', 'application/json');如果您返回大量JSON,则可以考虑创建一个路由组:
$app->group('/api', function () {
$this->response->withHeader('Content-Type', 'application/json');
$this->get(...);
$this->get(...);
}它可以节省时间,保持代码的整洁、可伸缩性和可维护性。
发布于 2016-04-13 12:02:59
请求对象有一个将数组转换为JSON并同时设置头部的方法。See documentation here
$app->get('/joinable', function ($request, $response, $args) {
return $response->withJson(getJoinable());
});只是getJoinable()需要返回一个数组,因为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,你可能也想要一个漂亮的json打印(对于较大的有效负载不建议,因为它增加了大约10-25%的传输字节大小):5.4+:
$app->get('/joinable', function ($request, $response, $args) {
return $response->write(json_encode(getJoinable(), JSON_PRETTY_PRINT))
->withHeader('Content-Type', 'application/json;charset=utf-8');
});https://stackoverflow.com/questions/35439409
复制相似问题