如何在Slim 3框架(PHP)中设置JSON标头? [英] How do I set a JSON header in Slim 3 framework (PHP)?
问题描述
如何在Slim 3中设置JSON标头?
How do I set a JSON header in Slim 3?
$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');
$response = $app->response();
$response['Content-Type'] = 'application/json';
$app->contentType('application/json');
推荐答案
Never used Slim framework, but according to their documentation, it should be something in the lines of:
$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是使用这些指南构建的.
What you are trying with header('Content-Type: application/json');
may actually work, but since you are using a framework for your application, you should respect their guidelines, or you'll end up with lots of problems. Also, that getJoinable()
is a global call, you should really learn some OOP and, more than that, follow the PSR guidelines, because Slim 3 is built using those guidelines.
这篇关于如何在Slim 3框架(PHP)中设置JSON标头?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!