如何在php中设置http响应状态代码和消息

ada*_*m78 10 php json httpresponse http-headers

我有页面检查通过HTTP POST(http://example.com/http_post)发送的数据.如果数据是好的,我添加到数据库并希望将http响应代码201和成功消息设置为http响应.如果不是我收集数组中的错误,并希望将http响应代码和消息设置为序列化JSON数组作为http响应.

1)什么是在PHP中将错误数组序列化为JSON的语法?

{
  "message": "The request is invalid.",
    "modelState": {
      "JobType": [ "Please provide a valid job type eg. Perm"]
  }
}
Run Code Online (Sandbox Code Playgroud)
  1. 是什么语法设置并将http响应返回到412.

  2. 是什么语法设置并返回http响应体中的序列化JSON,如上所述.

一个示例将有助于如何设置所有这些http响应标头.

谢谢

fir*_*ire 7

你可能正在寻找......

$arr = array('message' => 'blah'); //etc

header('HTTP/1.1 201 Created');
echo json_encode($arr);
Run Code Online (Sandbox Code Playgroud)