11

I have generated a site map .xml file and want to return. I placed the file in my views folder and made this route:

Route::get('/site-map', function(){
    return view('sitemap.xml');
});

Although I just cant get it to display.

Victori
  • 339
  • 2
  • 5
  • 17

1 Answers1

27

By default Laravel doesn't support loading .xml files as views. That being said, there are several solutions to your problem:

  • The easiest is to simply place your sitemap.xml in the /public directory. 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-Type header to application/xml or text/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 the register method of your AppServiceProvider, located at app/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');
    
Jonathon
  • 15,873
  • 11
  • 73
  • 92
  • You could you 'Content-Type' => 'text/xml' also, according to this answer: https://stackoverflow.com/a/4832418/2428101 – vinsa Oct 09 '20 at 11:12