【问题标题】:How do I set a JSON header in Slim 3 framework (PHP)?如何在 Slim 3 框架 (PHP) 中设置 JSON 标头?
【发布时间】:2018-05-28 04:36:40
【问题描述】:

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

【问题讨论】:

  • 我认为你必须添加一些细节,伙计......

标签: php json slim


【解决方案1】:

没用过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 是使用这些准则构建的。

【讨论】:

  • 好的,我试过了,它成功了,谢谢。但是出现了一个新问题:响应被缩短,导致数据丢失和 JSON 无效。
【解决方案2】:

您可以简单地执行以下操作(注意我使用的是内置的 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(...);
}

这样可以节省时间并让您的代码保持干净、可扩展和可维护。

【讨论】:

    【解决方案3】:

    请求对象有一个方法可以将数组转换为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');
    });
    

    【讨论】:

      【解决方案4】:

      首先,我建议对渲染器进行完全抽象。从长远来看更容易维护的一种。 例如,您可以使用此方法创建一个 Renderer 类:

      public function render(Response $response, array $data, $status_code)
      {
          return $response->withStatus((int) $status_code)
              ->withHeader('Content-Type', 'application/json;charset=utf-8')
              ->withJson($data);
      }
      

      其中$responseSlim\Http\Response 的一个实例。

      您可以在此处找到更强大的 Renderer 类:slim3-api-output-format

      希望这对其他人有所帮助。

      【讨论】:

        猜你喜欢
        • 2016-06-16
        • 2016-05-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-06-29
        • 2017-12-12
        • 2011-10-19
        相关资源
        最近更新 更多