Php 为什么yii2rest控制器以XML格式给出响应?
目前,我正在api模块上使用以下初始化代码Php 为什么yii2rest控制器以XML格式给出响应?,php,rest,yii2,Php,Rest,Yii2,目前,我正在api模块上使用以下初始化代码 public function init() { parent::init(); Yii::$app->response->format = Response::FORMAT_JSON; } 在下面的示例中,我的api以XML格式返回响应 public function actionTest() { $items = ['one', 'two', 'three' => ['a', 'b', 'c']];
public function init()
{
parent::init();
Yii::$app->response->format = Response::FORMAT_JSON;
}
在下面的示例中,我的api以XML格式返回响应
public function actionTest()
{
$items = ['one', 'two', 'three' => ['a', 'b', 'c']];
return $items;
}
以下是回应:
<response>
<item>one</item>
<item>two</item>
<three>
<item>a</item>
<item>b</item>
<item>c</item>
</three>
</response>
我测试了你的代码,它工作得很好 我的控制器:
<?php
namespace backend\controllers;
use yii\rest\Controller;
use yii;
use yii\web\Response;
class TestController extends Controller{
public function init()
{
parent::init();
Yii::$app->response->format = Response::FORMAT_JSON;
}
public function actionTest(){
$items = ['one', 'two', 'three' => ['a', 'b', 'c']];
return $items;
}
}
检查名称空间或发送代码 在Yii2应用程序中,默认的响应类型是XML(我猜REST也是默认的)。在HTTP连接期间,双方声明能够发送和/或接收的数据类型。如果未将此信息传递给服务器,则默认数据类型为send(即使您在应用程序中指定它应为JSON),以保证正确的通信。如果希望接收JSON数据,则必须将
Accept:application/JSON
头添加到请求中。而且您可能不必在php代码中指定它,因为Yi2应该从请求头中扣除它
你可以找到更多的解释。痛苦的三天后,我找到了解决办法。当您来自一个由ExpressJS和NodeJS组成的整个JSON世界时,有时很难解释这个问题。从逻辑上讲,Yii2所做的是非常好的,另一方面,90%的restfulapi希望输出是JSON格式的,因此您不希望每次调用API时都显式地设置请求头 默认情况下,浏览器将请求头添加为“Application/XML”,因此您在屏幕上看到的是XML而不是JSON Yii2的内容谈判者在收到标题时使用application/xml将输出格式化为xml。如果您使用CURL或PostMan(标题为“Application/JSON”)发出相同的请求,您将获得所需的输出 如果您希望覆盖此行为,则只需在控制器中添加以下功能,并包括以下内容:- 使用yii\web\Response; 使用yii\helpers\ArrayHelper
公共功能行为()
{
返回ArrayHelper::merge(父::行为()[
[
'class'=>'yii\filters\contentcongregator',
控制器中的“仅”=>[“视图”,“索引”],//为
//如果在模块中,请使用以下ID执行用户操作
//'仅'=>['用户/视图','用户/索引']
“格式”=>[
'application/json'=>Response::FORMAT_json,
],
“语言”=>[
"嗯",,
“德”,
],
],
]);
}
是否有其他行为或集体行动会改变您的应用程序响应格式?在返回值之前,您可以在任何操作中尝试使用var dumpingYii::$app->response->format
。我得到了以下XML解析错误:第1行第7列:字符串(3)“XML”---^该init()
属于我的模块类而不是控制器。实际上,这仍然给我XML响应。我有相同的配置,但它总是在浏览器上提供XML输出,在POSTMAN中提供JSON输出。这可能是由浏览器标题引起的。如果浏览器没有添加Accept:application/JSON
头,Yii可能不会发送JSON。@这应该是答案。我在Mozilla上通过修改标题对其进行了测试,现在可以正常工作了。把答案贴出来,我会接受的。
<?php
namespace backend\controllers;
use yii\rest\Controller;
use yii;
use yii\web\Response;
class TestController extends Controller{
public function init()
{
parent::init();
Yii::$app->response->format = Response::FORMAT_JSON;
}
public function actionTest(){
$items = ['one', 'two', 'three' => ['a', 'b', 'c']];
return $items;
}
}
{"0":"one","1":"two","three":["a","b","c"]}