Yii2 如何修改响应格式本身?

Yii2 如何修改响应格式本身?,yii2,response,formatter,Yii2,Response,Formatter,在一个动作中,我需要用一些XML进行响应。我使用Response::FORMAT_XML实现这一点,效果很好 // In a controller: public static function actionFetchData() { Yii::$app->response->format = Response::FORMAT_XML; return [ 'a' => 'b', ['c', 'd'], 'e'

在一个动作中,我需要用一些XML进行响应。我使用
Response::FORMAT_XML
实现这一点,效果很好

// In a controller:

public static function actionFetchData() {
    Yii::$app->response->format = Response::FORMAT_XML;

    return [
        'a' => 'b',
        ['c', 'd'],
        'e' => ['f', 'g']
    ];
}
在浏览器中显示结果:


. 我该怎么做


或者一般来说:如何更改格式化程序(也包括JSON或其他格式)的设置?

一种方法是为XML创建自己的格式化程序对象。原因:在
Yii::$app->response
中,formmatter不在操作中-它将在稍后创建,当响应呈现时,修改它已经太晚了。但是我们可以创建一个新的格式化程序,并将其设置为XML的格式化程序。这是一个有效的选择

public static function actionMetaInfo($docId) {
    $formatter = new XmlResponseFormatter([
        'rootTag' => 'data',
        'itemTag' => 'unnamed',
    ]);
    Yii::$app->response->formatters[Response::FORMAT_XML] = $formatter;
    Yii::$app->response->format = Response::FORMAT_XML;

    return [
        'a' => 'b',
        ['c', 'd'],
        'e' => ['f', 'g']
    ];
}
现在输出:



).

一种方法是为XML创建自己的格式化程序对象。原因:在
Yii::$app->response
中,formmatter不在操作中-它将在稍后创建,当响应呈现时,修改它已经太晚了。但是我们可以创建一个新的格式化程序,并将其设置为XML的格式化程序。这是一个有效的选择

public static function actionMetaInfo($docId) {
    $formatter = new XmlResponseFormatter([
        'rootTag' => 'data',
        'itemTag' => 'unnamed',
    ]);
    Yii::$app->response->formatters[Response::FORMAT_XML] = $formatter;
    Yii::$app->response->format = Response::FORMAT_XML;

    return [
        'a' => 'b',
        ['c', 'd'],
        'e' => ['f', 'g']
    ];
}
现在输出:



).

如果要修改所有应用程序的XML响应格式化程序,只需将其添加到配置文件中即可:

'components' => [
    'response' => [
        'formatters' => [
            'xml' => [
                'class' => 'yii\web\XmlResponseFormatter',
                'rootTag' => 'data',
            ],
        ],
    ],
],

如果要修改所有应用程序的XML响应格式化程序,只需将其添加到配置文件:

'components' => [
    'response' => [
        'formatters' => [
            'xml' => [
                'class' => 'yii\web\XmlResponseFormatter',
                'rootTag' => 'data',
            ],
        ],
    ],
],

如果要更改特定于特定操作的格式,请使用:

 Yii::$app->response->format = Response::FORMAT_XML;
 Yii::$app->response->formatters = [
        'xml' => [
            'class' => 'yii\web\XmlResponseFormatter',
            'rootTag' => 'data',
        ],
    ];

    return [
        'a' => 'b',
        ['c', 'd'],
        'e' => ['f', 'g']
    ];

如果要更改特定于特定操作的格式,请使用:

 Yii::$app->response->format = Response::FORMAT_XML;
 Yii::$app->response->formatters = [
        'xml' => [
            'class' => 'yii\web\XmlResponseFormatter',
            'rootTag' => 'data',
        ],
    ];

    return [
        'a' => 'b',
        ['c', 'd'],
        'e' => ['f', 'g']
    ];

小型优化:
Response::FORMAT\u XML
可以代替
'XML'
。小型优化:
Response::FORMAT\u XML
可以代替
'XML'