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?
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With