Symfony Controller - 如何返回XML响应?

时间:2014-10-08 09:13:05

标签: php xml symfony

我想在我的RandomController::indexAction() 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中打开这个动作时,我会进入firebug:

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

如何返回正确的XML响应?

2 个答案:

答案 0 :(得分:40)

尝试在响应对象上添加正确的标头,如:

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

否则在Controller方法中添加正确的注释(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 :(得分:1)

如果有很多XmlResponse要返回,请考虑创建自己的Response对象:

<?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',
        ]));
    }
}

然后您可以在控制器中返回new XmlResponse($xmlBody);