Yamen Nassif
Yamen Nassif

Reputation: 2476

Symfony Twig and xml - Document is empty error

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

Upvotes: 2

Views: 827

Answers (1)

Rapha&#235;l Mali&#233;
Rapha&#235;l Mali&#233;

Reputation: 4012

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.

Upvotes: 3

Related Questions