Trouble returning custom XML in API request

I am building an API where I am mostly returning JSON responses. However one third party service requires that some calls return XML. In the controller I can set the response format to FORMAT_XML but this wraps my content in <response> tags. The third party service requires that response to be wrapped in <Response> (note the case of R) tags.

So I need to either change the custom case the Yii2 creates or remove the default wrapper. Is this possible? Are there alternative methods that I could try.

This sounds stupid… but if I get you right, you’re returning entire XML response as string, right?

Therefore, right before returning it, you can use simple str_replace to replace <response> part with <Response> one.

I should have been more verbose. In my controller action I have this code:

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

return ['customer' => ['name' => 'John Smith']];

And Yii wraps the response in a response tag as such:



         <name>John Smith</name>



I don’t seem to have any control over the response tag.

OK, I’ve tried another approach and am almost there. Now I have the required XML in a view file which I am rendering which is giving me the exact output that I require, but it’s sending the Content-Type header as application/json or application/html depending on whether the controller extends Controller or ActiveController. If I try to force the format as XML it will wrap my preferred output again in response tags.

Try something like this.

$xml = new \yii\web\XmlResponseFormatter;

$xml->rootTag = 'Response';


Yii::$app->response->format = 'custom_xml';

Yii::$app->response->formatters['custom_xml'] = $xml;


return ['customer' => ['name' => 'John Smith']];

I really would like to know how to modify the formatter parameters easier.

Thanks Bizley,

This is the answer I was looking for. I just realised that this method does not allow for XML attributes but I discovered* that you can extend the XML format to have complete control so I will look at doing that at a later date.