Get response in JSON format in Yii2(在 Yii2 中获取 JSON 格式的响应)
问题描述
我正在尝试将响应数组转换为 JSON 格式.我已经尝试了在 SO 和其他网站上发布的所有答案,例如 web1,web2 添加 header('内容类型:application/json')
然后 echo json_encode($data,JSON_PRETTY_PRINT);
但我总是以文本格式获得输出.有人能帮我解决这个问题吗.
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,web2 adding 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.
助手类:
public static function renderJSON($data) {
header('Content-Type: application/json');
echo json_encode($data,JSON_PRETTY_PRINT);
}
我的控制器:
if ($model->login()) {
$user = User::findByUsernameOrEmail($request->post('username'));
$userArray = ArrayHelper::toArray($user);
Helpers::renderJSON($userArray);
我尝试打印 userArray
,它看起来像这样:
I tried to printing the userArray
and it looks like this:
Array
(
[name] => abc
[lastname] => xyz
[username] => test_test
)
Json 输出:(html/text)
Json output: (html/text)
{
"name": "abc",
"lastname": "xyz",
"username": "test_test"
}
推荐答案
设置
Yii::$app->response->format = yiiwebResponse::FORMAT_JSON;
在return
之前的某个控制器的动作中.
in the controller's action somewhere before return
.
这篇关于在 Yii2 中获取 JSON 格式的响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 Yii2 中获取 JSON 格式的响应


- Laravel 仓库 2022-01-01
- 没有作曲家的 PSR4 自动加载 2022-01-01
- 带有通配符的 Laravel 验证器 2021-01-01
- 从 PHP 中的输入表单获取日期 2022-01-01
- Oracle 即时客户端 DYLD_LIBRARY_PATH 错误 2022-01-01
- 正确分离 PHP 中的逻辑/样式 2021-01-01
- SoapClient 设置自定义 HTTP Header 2021-01-01
- Mod使用GET变量将子域重写为PHP 2021-01-01
- 如何定位 php.ini 文件 (xampp) 2022-01-01
- PHP Count 布尔数组中真值的数量 2021-01-01