Yii2 报错 Headers already sent in
有时候我们把Yii2 版本进行升级之后 会报一些莫名其妙的错误,这次就遇到如下错误信息
an Error occurred while handling another error: exception 'yii\web\HeadersAlreadySentException' with message 'Headers already sent in /xxxx/xxxx/xxx.php on line 90.' in /xxxx/xxxx/vendor/yiisoft/yii2/web/Response.php:366 Stack trace: #0 /xxxx/xxxx/vendor/yiisoft/yii2/web/Response.php(339): yii\web\Response->sendHeaders() #1 /xxxx/xxxx/vendor/yiisoft/yii2/web/ErrorHandler.php(135): yii\web\Response->send() #2/xxxx/xxxx/vendor/yiisoft/yii2/base/ErrorHandler.php(111): yii\web\ErrorHandler->renderException(Object(yii\web\HeadersAlreadySentException)) #3 [internal function]: yii\base\ErrorHandler->handleException(Object(yii\web\HeadersAlreadySentException)) #4 {main}
查阅了一些资料说,是因为使用json输出内容的时候 没有exit。以前的写法如下
protected function renderJSON($data=[], $msg ="ok", $code = 200) { header('Content-type: application/json'); echo json_encode([ "code" => $code, "msg" => $msg, "data" => $data, "req_id" => $this->geneReqId(), ]); return Yii::$app->end(); }
改成如下
protected function renderJSON($data=[], $msg ="ok", $code = 200) { $response = Yii::$app->response; $response->format = Response::FORMAT_JSON; $response->data = [ "code" => $code, "msg" => $msg, "data" => $data, "req_id" => $this->geneReqId(), ]; return $response; }
原文地址:Yii2 报错 Headers already sent in
标签:yii2 json header