25

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?

5
  • How do you build $randomParameter? Commented Oct 8, 2014 at 9:52
  • this is totally randomly randomed random string, for example $randomParameter = "randomParameter" :P I think it is not matter in this case ;) Commented Oct 9, 2014 at 7:57
  • But I don't understand why randomParameter remained untranslated by Twig. It should work even the response was not XML but HTML. Commented Oct 9, 2014 at 20:00
  • It works. Really. Just Value and Variable Name are the same ;) Commented Oct 10, 2014 at 6:21
  • I made edit special for you. Now, value and variable are different. Commented Oct 10, 2014 at 6:24

2 Answers 2

53

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

Sign up to request clarification or add additional context in comments.

3 Comments

Hi @user3766478 please consider to upvote my answer if you find it useful
I never new about the _format property of defaults - I'd always had to do away with annotating the template before because I needed to use the response object. Thanks for pointing it out!
@vladkras if you use annotations xml is enough.
11

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.

1 Comment

IMHO best solution - clean, transparent and no code repetitions

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.