Yii2, data output in the form of an XML document

February 12, 2019 50 Yehor Rykhnov

There are many options when you need to display data as XML document. For example, when you need to display the contents of the sitemap.xml for a search engine.

XML in Yii2, Option 1

public function actionTest() {
    \Yii::$app->response->format = \yii\web\Response::FORMAT_XML;
    return $this->renderPartial('test');
}

In line 2, the code \yii\web\Response can be moved to use, then the code will be as follows:

<?php
//...
use yii\web\Response;
//...
public function actionTest() {
    \Yii::$app->response->format = Response::FORMAT_XML;
    return $this->renderPartial('test');
}

XML in Yii2, Option 2

With help behaviors:

<?php
//...
public function behaviors() {
    return [
        [
            'class' =>  \yii\filters\ContentNegotiator::className(), //can be moved to use yii\filters\ContentNegotiator
            'only' => ['xml'], //action name
            'formats' => [
                'text/xml' => Response::FORMAT_XML,
            ],
        ],
    ];
}
public function actionTest() {
    return $this->renderPartial('test');
}

Here \yii\filters\ContentNegotiator can be moved to use. Also, consider an option when the behaviors method already exists:

<?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 in Yii2, Option 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 can be moved to use.

It is worth noting that in all options, the view is displayed using renderPartial without the main layout.


xml