Get your JSON response - yii2 and php

I am trying to convert and massage the response in JSON format. I tried all the answers that were posted on SO and other websites like web1 , web2 adding header('Content-Type: application/json') and then echo json_encode($data,JSON_PRETTY_PRINT); But I always get the output in text format. Can someone help me in resolving this issue.

Helper Class:

 public static function renderJSON($data) { header('Content-Type: application/json'); echo json_encode($data,JSON_PRETTY_PRINT); } 

My controller:

 if ($model->login()) { $user = User::findByUsernameOrEmail($request->post('username')); $userArray = ArrayHelper::toArray($user); Helpers::renderJSON($userArray); 

I tried to print userArray and it looks like this:

 Array ( [name] => abc [lastname] => xyz [username] => test_test ) 

Json output: (html / text)

 { "name": "abc", "lastname": "xyz", "username": "test_test" } 
+5
source share
2 answers

Set

 \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON; 

in the controller action somewhere before return .

+16
source

Just add this to the controller

 public function beforeAction($action) { \Yii::$app->response->format = Response::FORMAT_JSON; return parent::beforeAction($action); } 
+2
source

Source: https://habr.com/ru/post/1262873/


All Articles