P
P
Petya Fox2019-05-28 20:50:06
RSS
Petya Fox, 2019-05-28 20:50:06

How to generate RSS feed for Laravel?

Guys, how to generate RSS feed for Laravel without any additional packages? I tried, but for some reason my XML tags were executed on the client.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
P
Petya Fox, 2019-05-28
@fullstackru

I found a solution for the sitemap, the error for the RSS feed was fixed in the same way. {{ Request::header('Content-Type : text/xml') }} - sets the desired content type.
It was :

<?php
header("Content-Type: text/xml;charset=iso-8859-1"); // Здесь была ошибка
echo '<?xml version="1.0" encoding="UTF-8"?>';
?>
 
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
    @foreach ($posts as $post)
        <url>
            <loc>{{ url($post->slug) }}</loc>
            <lastmod>{{ $post->updated_at->tz('GMT')->toAtomString() }}</lastmod>
            <changefreq>monthly</changefreq>
            <priority>1</priority>
        </url>
    @endforeach
</urlset>

Fixed :
{{ Request::header('Content-Type : text/xml') }}
<?php echo '<?xml version="1.0" encoding="UTF-8"?>';?>
 
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
    @foreach ($posts as $post)
        <url>
            <loc>{{ url($post->slug) }}</loc>
            <lastmod>{{ $post->updated_at->tz('GMT')->toAtomString() }}</lastmod>
            <changefreq>monthly</changefreq>
            <priority>1</priority>
        </url>
    @endforeach
</urlset>

Also, if you want to use PHP support inside XML files, you can add the following line to your .htaccess file:
AddType application/x-httpd-php .php .xml
php_flag short_open_tag off

You can also specify the type in the controller itself:
public function index()
    {
      $articles = Article::all()->first();
      $categories = Category::all()->first();
      $questions = Question::all()->first();
      $tags = Tag::all()->first();

      return response()->view('sitemap.index', [
          'articles' => $articles,
          'categories' => $categories,
          'questions' => $questions,
          'tags' => $tags,
      ])->header('Content-Type', 'text/xml');
    }

But I made it a little simpler:
public function sitemap() {
  $articles = DB::table('articles')->orderBy('id', 'desc');

  return response()->view('sitemap', [
    'articles' => $articles,
  ])->header('Content-Type', 'text/xml');
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question