Skip to content

JSON

在最简单的形式下,可以使用默认的 200 HTTP 状态码返回 JSON 数据。

$data = array('name' => 'Bob', 'age' => 40);
$payload = json_encode($data);

$response->getBody()->write($payload);
return $response
          ->withHeader('Content-Type', 'application/json');

我们也可以使用自定义的 HTTP 状态码返回 JSON 数据。

$data = array('name' => 'Rob', 'age' => 40);
$payload = json_encode($data);

$response->getBody()->write($payload);
return $response
          ->withHeader('Content-Type', 'application/json')
          ->withStatus(201);

Info

Response 对象是不可变的。该方法返回一个新的 Response 对象副本,其中包含新的 Content-Type 头部。这个方法是破坏性的,它将替换掉已存在的 Content-Type 头部。

返回重定向

你可以使用 Location 头部来实现 HTTP 客户端的重定向。

return $response
  ->withHeader('Location', 'https://www.example.com')
  ->withStatus(302);