Sometimes we put after Yii2 version upgrade will report some inexplicable error, this time to encounter the following error message
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}
Access to some information that is because the use of json output content when there is no exit. Previous wording as follows
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(); }
Read as follows
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; }
Original Address: Yii2 Headers already sent in error
Tags: yii2 json header