Symfony Twig and xml - Document is empty error

Question

since the declaring of xml should happen in the first line and an empty line being added to the beginning of the rendered file which causing this error

so the question is how to remove the empty line from the beginning of the document? or is there any other way - not bundles- to use sitemaps?

twig

<?xml version="1.0"?>
<?xml-stylesheet type="text/xsl" href="{{asset("sitemap.xsl")}}"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
{% for url in urls %}
    <url>{# check if hostname is not alreay in url#}
        <loc>{{url.loc}}</loc>
    </url>
{% endfor %}
</urlset>

controller

<?php

namespace MarketplaceBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Component\HttpFoundation\Response;
// use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;

class SitemapController extends Controller
{
    /**
     * @Route("/sitemap.{_format}", name="marketplace_sitemap", Requirements={"_format" = "xml"})
     */
    public function sitemapAction()
    {
        $urls = array();

        // add some urls homepage
        $urls[] = array('loc' => $this->get('router')->generate('marketplace'), 'changefreq' => 'weekly', 'priority' => '1.0');

        // service


        $response = new Response(
                                $this->render("MarketplaceBundle:sitemap:sitemap.xml.twig",
                                    array('urls' => $urls) ),
                                200,
                                array('Content-Type' => 'application/xml')
                                );
        return $response;
    }
}

when using this code i always get the error :

error

enter image description here


Show source
| xml   | symfony2   | twig   2017-01-04 16:01 1 Answers

Answers ( 1 )

  1. 2017-01-04 16:01

    Try this :

        $response = $this->render("MarketplaceBundle:sitemap:sitemap.xml.twig", array(
            'urls' => $urls
        ));
        $response->headers->add(array('Content-Type' => 'application/xml'));
        return $response;
    

    $this->render() already return a response, so you don't need to embed it in another Response object.

◀ Go back