2014-10-08 42 views
14

我想在我的RandomController::indexAction()返回XML响应:Symfony Controller - 如何返回XML响应?

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

其中index.xml.twig是这样的:

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

当我想在Firefox中打开这个动作,我得到的萤火:

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

如何返回正确的XML响应?

+0

怎么办你建立'$ randomParameter'? – COil 2014-10-08 09:52:10

+0

这是完全随机随机随机字符串,例如$ randomParameter =“randomParameter”:P我认为这不是问题;) – user3766478 2014-10-09 07:57:48

+0

但我不明白为什么'randomParameter'仍然未被Twig转译。它应该工作,即使响应不是XML而是HTML。 – COil 2014-10-09 20:00:47

回答

36

尝试,如响应对象添加正确的标题:

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

否则你的控制器的方法添加正确的注释(defaults)这样的例子:

/** 
    * @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

+1

我用第一,它运作良好,所以谢谢:) – user3766478 2014-10-09 07:55:18

+0

嗨@ user3766478请考虑upvote我的答案,如果你觉得它有用 – Matteo 2015-01-22 08:38:02

+1

我从来没有新的_format属性的默认值 - 我总是不得不取消注释之前的模板,因为我需要使用响应对象。感谢您指出! – 2016-01-20 23:38:20