如何在 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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 17:48:12  来源:igfitidea点击:

How to return a .xml file in a Laravel Route

phplaravellaravel-5sitemap

提问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 .xmlfiles as views. That being said, there are several solutions to your problem:

默认情况下,Laravel 不支持将.xml文件加载为视图。话虽如此,您的问题有几种解决方案:

  • The easiest is to simply place your sitemap.xmlin the /publicdirectory. The browser will be able to see the file at http://yourdomain.com/sitemap.xml.

  • You could load the contents of your file and return a response, setting the Content-Typeheader to application/xmlor text/xmlto 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 .xmlextension by doing something like this in a service provider (such as the registermethod of your AppServiceProvider, located at app/Providers/AppServiceProvider.php):

    app('view.finder')->addExtension('xml');
    

    Once you've done that, Laravel should recognise .xmlas 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/xmltext/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');