Symfony Controller - How to return XML response?
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.
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