Skip to content

Instantly share code, notes, and snippets.

@atakde
Created September 5, 2022 17:58
Show Gist options
  • Save atakde/5f2a8ffd291531ce341e4414a0a14703 to your computer and use it in GitHub Desktop.
Save atakde/5f2a8ffd291531ce341e4414a0a14703 to your computer and use it in GitHub Desktop.
Symfony 6 Sitemap Generator
<?php
namespace App\Controller;
use App\Repository\PostRepository;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
class SitemapController extends AbstractController
{
public function __construct(PostRepository $blogPostRepository)
{
$this->blogPostRepository = $blogPostRepository;
}
#[Route('/sitemap.xml', name: 'sitemap')]
public function index()
{
// find published blog posts from db
$posts = $this->blogPostRepository->findBy(['published' => 1]);
$urls = [];
foreach ($posts as $post) {
$urls[] = [
'loc' => $this->generateUrl(
'post',
['slug' => $post->getSlug()],
UrlGeneratorInterface::ABSOLUTE_URL
),
'lastmod' => $post->getUpdatedAt()->format('Y-m-d'),
'changefreq' => 'weekly',
'priority' => '0.5',
];
}
$response = new Response(
$this->renderView('./sitemap/sitemap.html.twig', ['urls' => $urls]),
200
);
$response->headers->set('Content-Type', 'text/xml');
return $response;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment