Symfony2强制twig输出XML格式的数据

时间:2015-01-07 12:35:38

标签: php xml symfony sitemap

我正在使用Symfony2并努力使用twig以XML格式输出数据。相反,twig只会将大量文本块抛到浏览器上,只有当右键单击查看源代码时,我才能看到布局合理的XML。

有没有什么方法可以强制Twig实际输出格式化的XML而不是查看页面源...?

sitemap.xml.twig:

<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
    <url>
        {% for entry in sitemapresp %}
            <loc>{{ entry['url'] }}</loc>
            <lastmod>{{ entry['date'] }}</lastmod>
            <changefreq>{{ entry['frequency'] }}</changefreq>
            <priority>{{ entry['priority'] }}</priority>

        {% endfor %}
    </url>
</urlset>

浏览器输出:

http://www.sitemappro.com/2015-01-27T23:55:42+01:00daily0.5http://www.sitemappro.com/download.html2015-01-26T17:24:27+01:00daily0.5

源视图输出:

    <?xml version="1.0" encoding="UTF-8"?>
    <urlset xmlns="http://www.google.com/schemas/sitemap/0.90">
      <url>
        <loc>http://www.sitemappro.com/</loc>
        <lastmod>2015-01-27T23:55:42+01:00</lastmod>
        <changefreq>daily</changefreq>
        <priority>0.5</priority>
      </url>
      <url>
        <loc>http://www.sitemappro.com/download.html</loc>
        <lastmod>2015-01-26T17:24:27+01:00</lastmod>
        <changefreq>daily</changefreq>
        <priority>0.5</priority>
      </url>
</urlset>

有什么建议吗??

3 个答案:

答案 0 :(得分:10)

如果您需要将该页面设置为XML,则需要设置响应的内容类型。

$response = new Response($this->render('sitemap.xml.twig'));
$response->headers->set('Content-Type', 'application/xml; charset=utf-8');
return $response;

如果您只想要部分页面在HTML页面中呈现代码,请使用:

{% autoescape %}
<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
    <url>
        {% for entry in sitemapresp %}
            <loc>{{ entry['url'] }}</loc>
            <lastmod>{{ entry['date'] }}</lastmod>
            <changefreq>{{ entry['frequency'] }}</changefreq>
            <priority>{{ entry['priority'] }}</priority>

        {% endfor %}
    </url>
</urlset>
{% endautoescape %}

答案 1 :(得分:7)

控制器端:

$response = new Response();
$response->headers->set('Content-Type', 'xml');
return $this->render(
   'Bundle:Controller:sitemap.xml.twig',
   array(
        'param1' => $param1,// ...
   ),
   $response
);

答案 2 :(得分:1)

您必须只渲染视图才能将其发送到响应。

$response = new Response($this->renderView('sitemap.xml.twig'));
$response->headers->set('Content-Type', 'application/xml; charset=utf-8');
return $response;

所以用$this->render(...)

替换$this->renderView(...)

HTTP/1.0 200 OK Cache-Control: no-cache....将消失