Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Brotzka's avatar

Generate a sitemap -> use Blade for xml-document

Hello together,

I try to build a sitemap. I have defined a route like Route::get('/sitemap', 'SitemapController@sitemap);

In my SitemapController I use the XMLWriter-Class. But I like to use a Blade view if possible.

Is it possible to use a Blade view for a sitemap? If yes, how?

Thanks!

0 likes
5 replies
martinbean's avatar
Level 80

@Brotzka Have you tried anything?

<!-- resources/views/xml/sitemap.blade.php -->
<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
  @​foreach($pages as $page)
     <url>
        <loc>{{ $page->url }}</loc>
        <lastmod>{{ $page->updated_at->toAtomString() }}</lastmod>
     </url>
  @​endforeach
</urlset> 

Just make sure to set the correct Content-Type header in your controller action:

class SiteMapController extends Controller
{
    public function index()
    {
        $pages = Page::all();

        return response()->view('xml.sitemap', compact('pages'))->header('Content-Type', 'text/xml');
    }
}
6 likes
Brotzka's avatar

Thanks! That is what I was looking for. Didn't know, that I could return a response like that.

mbpp's avatar

IS giving me a error: FatalErrorException in 6955f07d83b93bb8aa89577b116866e228e0c155.php line 1: syntax error, unexpected 'version' (T_STRING) My bladE:

<?xml version="1.0"?>
<rss xmlns:g="http://base.google.com/ns/1.0" version="2.0">
  <channel>
    <title>Test Store</title>
    <link>http://domain.com</link>
    <description>An example item from the feed</description>
   @​foreach($products as $product)
      <item>
      <g:id>1</g:id>
      <g:title>something</g:title>
      <g:description>Solid plastic Dog Bowl in marine blue color</g:description>
      <g:link>http://www.zara.com</g:link>
      <g:image_link>http://domain.com/images/photos_gallery/14788772681.png</g:image_link>
      <g:price>12 GBP</g:price>
      <g:brand>Nike</g:brand>
       <g:availability>in stock</g:availability>
       <g:condition>new</g:condition>
    </item>
  @​endforeach
  </channel>
</rss>

Does anybody no what could be wrong?

Quero's avatar

Maybe PHP Short Tags are on! i nobody have a better solution just disable short tags on server or make:

<?php
echo '<?xml version="1.0"?>';
?>

in blade..

2 likes

Please or to participate in this conversation.