I am using Symfony2 and struggling to use twig to output data in a XML format. Instead what happens twig just throws massive block of text on to the browser it is only when right click to view source i can see nicely laid out XML.
Is there any way I can force Twig to actually output formatted XML instead blok of text without having to view page source...?
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>
Browser Output:
http://www.sitemappro.com/2015-01-27T23:55:42+01:00daily0.5http://www.sitemappro.com/download.html2015-01-26T17:24:27+01:00daily0.5
Source View Output:
<?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>
Any suggestions..?
If you need the page to be XML, you will need to set the content type of the response.
$response = new Response($this->render('sitemap.xml.twig'));
$response->headers->set('Content-Type', 'application/xml; charset=utf-8');
return $response;
If you only want part of the page to render the code in an HTML page, use:
{% 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 %}