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.