php 在 Yii2 中获取 JSON 格式的响应

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/41675051/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 02:26:36  来源:igfitidea点击:

Get response in JSON format in Yii2

phpjsonyii2yii2-advanced-app

提问by ASN

I'm trying to convert and array of response into JSON format. I have tried all the answers that were posted on SO and other websites like web1,web2adding header('Content-Type: application/json')and then echo json_encode($data,JSON_PRETTY_PRINT);But I'm always getting the output in text format. Can some one help me in solving this.

我正在尝试将响应数组转换为 JSON 格式。我已经尝试了在 SO 和其他网站上发布的所有答案,如web1web2添加header('Content-Type: application/json')然后echo json_encode($data,JSON_PRETTY_PRINT);但我总是以文本格式获得输出。有人可以帮我解决这个问题吗?

Helpers 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 printing the userArrayand it looks like this:

我试图打印它userArray,它看起来像这样:

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

Json output: (html/text)

Json 输出:(html/文本)

{
    "name": "abc",
    "lastname": "xyz",
    "username": "test_test"
}

回答by Bizley

Set

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

in the controller's action somewhere before return.

在控制器之前某处的动作中return

回答by Andreas Hinderberger

Since Yii 2.0.11 there is a dedicated asJson()method to return a response in JSON format. Run:

从 Yii 2.0.11 开始,有一个专门的asJson()方法以 JSON 格式返回响应。跑:

return $this->asJson($array);

in your controller action.

在您的控制器操作中。

回答by Yasar Arafath

Simply Add this in controller

只需在控制器中添加它

public function beforeAction($action)
{

    \Yii::$app->response->format = Response::FORMAT_JSON;
    return parent::beforeAction($action);
}

回答by manglide

use yii\helpers\Json;
use yii\web\Response;

Firstly include the 2 lines above at the top of your controller, then in any of your Controller actions, just before the return statements, include the below

首先在您的控制器顶部包含上面的 2 行,然后在您的任何控制器操作中,就在 return 语句之前,包含以下内容

Yii::$app->response->format = Response::FORMAT_JSON;
return Json::encode([
            'message' => 'success'
]);

You can build the return array as you deem fit.

您可以根据需要构建返回数组。