如何在 Laravel 路由中返回 .xml 文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/50767373/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to return a .xml file in a Laravel Route
提问by Victori
I have generated a site map .xml file and want to return. I placed the file in my views folder and made this route:
我生成了一个站点地图 .xml 文件并想返回。我将文件放在我的视图文件夹中并制作了这条路线:
Route::get('/site-map', function(){
return view('sitemap.xml');
});
Although I just cant get it to display.
虽然我只是不能让它显示。
回答by Jonathon
By default Laravel doesn't support loading .xml
files as views. That being said, there are several solutions to your problem:
默认情况下,Laravel 不支持将.xml
文件加载为视图。话虽如此,您的问题有几种解决方案:
The easiest is to simply place your
sitemap.xml
in the/public
directory. The browser will be able to see the file athttp://yourdomain.com/sitemap.xml
.You could load the contents of your file and return a response, setting the
Content-Type
header toapplication/xml
ortext/xml
to tell the browser that the file you're serving is in fact an XML document.return response(file_get_contents(resource_path('sitemap.xml')), 200, [ 'Content-Type' => 'application/xml' ]);
Alternatively, you could tell Laravel's view finder to support the
.xml
extension by doing something like this in a service provider (such as theregister
method of yourAppServiceProvider
, located atapp/Providers/AppServiceProvider.php
):app('view.finder')->addExtension('xml');
Once you've done that, Laravel should recognise
.xml
as a valid view extension and load your XML file as if it was a view. This has the added benefit of being able to pass data to it and use Blade/PHP within your view, if you want to:return view('sitemap');
最简单的方法是简单地将您的
sitemap.xml
放在/public
目录中。浏览器将能够在http://yourdomain.com/sitemap.xml
.您可以加载文件的内容并返回响应,将
Content-Type
标头设置为application/xml
或text/xml
告诉浏览器您提供的文件实际上是一个 XML 文档。return response(file_get_contents(resource_path('sitemap.xml')), 200, [ 'Content-Type' => 'application/xml' ]);
或者,您可以
.xml
通过在服务提供者中执行类似操作来告诉 Laravel 的取景器支持扩展(例如register
您的方法AppServiceProvider
,位于app/Providers/AppServiceProvider.php
):app('view.finder')->addExtension('xml');
一旦你这样做了,Laravel 应该识别
.xml
为一个有效的视图扩展并加载你的 XML 文件,就好像它是一个视图一样。如果您想:return view('sitemap');