XML в Yii2, варіант 1
public function actionTest() {
\Yii::$app->response->format = \yii\web\Response::FORMAT_XML;
return $this->renderPartial('test');
}
У рядку 2, код \yii\web\Response можна перенести до use, тоді код буде наступний:
<?php
//...
use yii\web\Response;
//...
public function actionTest() {
\Yii::$app->response->format = Response::FORMAT_XML;
return $this->renderPartial('test');
}
XML в Yii2, варіант 2
За допомогою behaviors:
<?php
//...
public function behaviors() {
return [
[
'class' => \yii\filters\ContentNegotiator::className(), //можем перенести в use yii\filters\ContentNegotiator
'only' => ['xml'], //название действия
'formats' => [
'text/xml' => Response::FORMAT_XML,
],
],
];
}
public function actionTest() {
return $this->renderPartial('test');
}
У цьому варіанті також \yii\filters\ContentNegotiator можна перенести до use. Також розглянемо варіант коли метод behaviors вже існує:
<?php
//...
namespace frontend\controllers;
//...
use yii\filters\ContentNegotiator;
use yii\web\Response;
class SiteMapController extends BaseController
{
public function behaviors() {
return [
'access' => [
'class' => AccessControl::className(),
'only' => ['logout'],
'rules' => [
[
'actions' => ['logout'],
'allow' => true,
'roles' => ['@'],
],
],
],
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'logout' => ['post'],
],
],
[
'class' => ContentNegotiator::className(),
'only' => ['test'],
'formats' => [
'text/xml' => Response::FORMAT_XML,
],
],
];
}
//...
public function actionTest() {
return $this->renderPartial('test');
}
}
XML в Yii2, варіант 3
public function actionTest() {
Yii::$app->response->format = \yii\web\Response::FORMAT_RAW;
Yii::$app->response->headers->add('Content-Type', 'text/xml');
return $this->renderPartial('test');
}
\yii\web\Response можна перенести до use.
Варто зауважити, що в усіх варіантах в'юшка виводиться за допомогою renderPartial без основного лайаута.


