因为 xml 的声明应该发生在第一行,并且空行被添加到渲染文件的开头,从而导致此错误
那么问题是如何删除文档开头的空行?或者有没有其他方式(不是捆绑)来使用站点地图?
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;
}
}
使用此代码时我总是收到错误:
错误
最佳答案
试试这个:
$response = $this->render("MarketplaceBundle:sitemap:sitemap.xml.twig", array(
'urls' => $urls
));
$response->headers->add(array('Content-Type' => 'application/xml'));
return $response;
$this->render()
已返回响应,因此您无需将其嵌入到另一个 Response
对象中。
关于xml - Symfony Twig 和 xml - 文档为空错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41467280/