如何在Slim 3框架(PHP)中设置JSON标头? [英] How do I set a JSON header in Slim 3 framework (PHP)?

查看:122
本文介绍了如何在Slim 3框架(PHP)中设置JSON标头?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在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');

推荐答案

从未使用过Slim框架,但根据

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆