Setting content type of Yii2 action output to XML

I had some issues finding the right part of the documentation in Yii2 to set the content-type of an action output (rendered view) to XML (content-type: application/xml; charset=UTF-8).

It turned out that it is quite simple once you got digged out the Response class and how to use it.

In your action-function use this lines to set the output format to xml:

The first line will set Response to RAW format (The Yii2 doucmentaiton says ‚use this format if you want to send the response directly without applying any formatting.‘)
The second line gets the headers instance and the third line add the header for the Content-Type and set it to XML.
You might want to add another header for the Charset as well by replacing the third line e.g. with:

Once this is done Yii2 will send the correct header in the reponse to the browser.

You could then either directly echo-out the xml content in the action-method itself or use a view which does the rendereing of the content.

You might need to disabled the layout before rendering the view or simply call „renderPartial“ method to skip the layout.

Here is a complete example of rendering some content as xml using a view:

A very simple view (named xmlview.php in this example ) file could look something like this (obviously you could just as well use some XML-API to build up the node-tree but for this example I keep it simple and lightweight):

now you can call you action and should get the xml displayed correctly in the browser with the correct content type beeing send in the headers.


  • Jc

    Creating xml as response is not recommended for most of the instance.
    But if you really want/need to generate a simple xml response without cascading objects., I think it will be simpler if you just use:

    Yii::$app->response->format = \yii\web\Response::FORMAT_XML;

    or just use

    Yii::$app->response->format = ‚xml‘;

    Then, just return the array you want to format such as:

    Yii::$app->response->format = \yii\web\Response::FORMAT_XML;
    //set up some dummy values to be rendered
    $xmlValues = [‚test1‘ => ‚value1‘, ‚test2‘ => ‚value2‘];
    return $xmlValue;

    The thing with this method will be:
    1. You can not set property of an item;
    2. If you a working with Objects coming from database, you have to format if first to double dimesional array;

  • Ilya

    Both of these methods didn’t work if your ourput is large.

    „Creating xml as response is not recommended for most of the instance.“ – Why ?

Schreibe einen Kommentar

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert.

This site uses Akismet to reduce spam. Learn how your comment data is processed.