繁体   English   中英

使用laravel渲染站点地图时出错

[英]error rendering a sitemap with laravel

我在使用laravel渲染站点地图时遇到问题。 生成的xml似乎还可以,但是当我尝试从chrome或firefox调用url时出现错误

 error on line 2 at column 6: XML declaration allowed only at the start of the document

实际上,文档的第1行为空,并且xml声明从第2行开始

这是我的代码:

 return Response::view('sitemap.index', ['agences' => $agences])->header('Content-Type', 'application/xml');

我也尝试过这种语法:

 $xml = View::make('sitemap.index', ['agences' => $agences]);
 return Response::make($xml, 200)->header('Content-Type', 'application/xml');

这样我可以做

 dd($xml->render()); 

并意识到返回的字符串没有空的第一行。 所以我猜是Response :: make是要怪的,但我真的不知道从哪里看

好吧,我要发表我自己的答案,原因很棘手,而且花了我一天的时间,好消息是我对laravel的了解略有增加。

所以我的xml站点地图以空行开头,这在浏览器上造成了错误。 Xml首先使用刀片模板生成。 由于不起作用,我决定使用RoumenDamianoff / laravel-sitemap

但是我有同样的问题。 所以最后我决定再次使用SimpleXmlElement自己生成Xml,并且它什么都没有改变。

从那时起,我开始挖掘Laravel内部的,以查看该空行可能来自请求生命周期。

基本上我的站点地图非常简单:

$urlset = new SimpleXMLElement('<?xml version="1.0" encoding="UTF-8"?><urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:image="http://www.google.com/schemas/sitemap-image/1.1" /><!--?xml version="1.0" encoding="UTF-8"?-->');
datas = MyModel::All();
foreach($datas as $index=>$data){
// generate sitemap
}
$dom = new DomDocument();
$dom->loadXML($urlset->asXML());
$dom->formatOutput = true;
//output xml
$xml = $dom->saveXML();
$response = Response::make($xml, 200, ['Content-Type' => 'application/xml']);

为了测试,我决定更改我要的模型,然后生成的xml没有第一个空行。 因此,我决定调查模型本身并找到错误。 在php开头标记之前,模型文件只有一个空行。

删除空行解决了我的问题....

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM