Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony Controller - How to return XML response?

Tags:

I want to return in my RandomController::indexAction() an XML Response:

return new Response($this->renderView(     'AcmeRandomBundle:Random:index.xml.twig',     array(         'randomParameter' => $randomParameter     ) )); 

where index.xml.twig is like that:

<?xml version="1.0" encoding="UTF-8"?> <randomTag>     {{ randomParameter }} </randomTag> 

When I want to open this action in firefox, I get in firebug:

<html>    <body>     <randomTag>         randomValue     </randomTag>    </body> </html> 

How to return correct XML response?

like image 635
user3766478 Avatar asked Oct 08 '14 09:10

user3766478


2 Answers

Try adding correct header on the Response Object like:

$response->headers->set('Content-Type', 'text/xml'); 

Otherwise add the correct annotation (defaults) on your Controller method like this example:

 /**   * @Route("/hello/{name}", defaults={"_format"="xml"}, name="_demo_hello")   * @Template()   */   public function helloAction($name)   {      return array('name' => $name);   } 

Look at the guide for further explaination

like image 171
Matteo Avatar answered Oct 18 '22 07:10

Matteo


If you have many XmlResponse to return, consider creating your own Response object:

<?php  namespace App\Component\HttpFoundation;  use Symfony\Component\HttpFoundation\Response;  class XmlResponse extends Response {     public function __construct(?string $content = '', int $status = 200, array $headers = [])     {         parent::__construct($content, $status, array_merge($headers, [             'Content-Type' => 'text/xml',         ]));     } } 

You can then return new XmlResponse($xmlBody); in your controllers.

like image 32
Alain Tiemblo Avatar answered Oct 18 '22 09:10

Alain Tiemblo