How to create a sitemap.xml on Symfony Blog without Bundle

Sd404
4 min readJul 31, 2023

--

Photo by Markus Winkler on Unsplash

A sitemap.xml is a vital tool for enhancing your website’s search engine optimization and improving its visibility on search engines. While Symfony has a dedicated bundle for generating sitemaps, it is also possible to create a sitemap without using a bundle. In this step-by-step guide, we’ll show you how to generate a sitemap.xml in Symfony without relying on a specific bundle, allowing you to have more control over the process.

What is an XML sitemap and why should you have one?

A sitemap.xml is a file that provides information to search engines about the structure and content of a website. It is an essential tool for search engine optimization (SEO) as it helps search engine crawlers (also known as bots or spiders) to navigate and index the pages on a website more effectively.

The sitemap.xml is written in XML (Extensible Markup Language) format and follows a specific schema defined by the sitemaps.org protocol. It contains a list of URLs (Uniform Resource Locators) that represent the different pages on the website that the website owner wants to be indexed by search engines.

Each URL in the sitemap.xml may include additional information, such as the last modification date, the frequency of change (e.g., always, hourly, daily, weekly, etc.), and a priority value that indicates the relative importance of the URL compared to other URLs on the site.

The primary purpose of a sitemap.xml is to inform search engines of the website’s structure and ensure that all relevant pages are discovered and indexed promptly. By providing this information to search engines, website owners can improve their website’s visibility in search engine results and increase the likelihood of their pages being ranked higher for relevant search queries.

It’s important to note that a sitemap.xml is not a guarantee that all pages will be indexed, but it is a useful tool to facilitate the indexing process for search engines. Additionally, sitemaps are not only beneficial for larger websites with many pages; even smaller websites can benefit from having a sitemap.xml to improve their search engine visibility.

The Required Dependencies

To start, ensure you have Symfony installed and your Symfony project up and running. Next, you’ll need to install the twig/twig packages using Composer. The twig/twig package is essential for rendering the XML content.

Define the Sitemap Controller

Create a new controller named SitemapController.php. This controller will handle the logic to generate the sitemap. In the controller, import the necessary classes and set up the action that will generate the sitemap:

In the example bellow, we have two kind of URL :

  • Static : Like homepage or Policy page
  • Dynamic: for articles
namespace App\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use App\Repository\PostRepository;

class SitemapController extends AbstractController
{
public function __construct(PostRepository $postRepository)
{
$this->postRepository = $postRepository;
}

#[Route('/sitemap.{_format}', name: 'app_sitemap', requirements: ['_format' => 'html|xml'], format: 'xml')]
public index(Request $request): Response
{
$hostname = $request->getSchemeAndHttpHost();

$urls = []; // Array to store sitemap URLs

// Add your sitemap URLs dynamically (e.g., from database or routes)

// Static URLs
$urls[] = ['loc' => $this->generateUrl('app_home'), 'priority' => '1.00'];

// Dynamic URLs from Post table
$posts = $this->postRepository->findBy(['language' => $language]);
foreach ($posts as $post)
{
$urls[] = [
'loc' => $this->generateUrl('post_show', [
'slug' => $post->getSlug(),
]),
'priority' => '1.00',
'lastmod' => $post->getUpdatedAt()->format('Y-m-d')
];
}

$xml = $this->renderView('sitemap/sitemap.xml.twig', [
'urls' => $urls,
'hostname' => $hostname
]);


return new Response($xml, 200, ['Content-Type' => 'text/xml']);
}
}

The $urls loc key for location, priority to classify location last modification date.

For a blog you can even add priority to your Post table, so you can set article priority dynamically.

Create the sitemap.xml.twig Template

The Twig template will be used to render the sitemap in XML format.

<?xml version="1.0" encoding="UTF-8"?>
<urlset
xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"
xmlns:xhtml="http://www.w3.org/1999/xhtml"
xmlns:image="http://www.google.com/schemas/sitemap-image/1.1"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9
http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd">
{% for url in urls %}
<url>
{% if url.loc|replace({hostname:''}) == url.loc %}
<loc>{{ hostname }}{{ url.loc }}</loc>
{% else %}
<loc>{{ url.loc }}</loc>
{% endif %}
{% if url.lastmod is defined %}
<lastmod>{{ url.lastmod }}</lastmod>
{% endif %}
{% if url.changefreq is defined %}
<changefreq>{{ url.changefreq }}</changefreq>
{% endif %}
{% if url.priority is defined %}
<priority>{{ url.priority }}</priority>
{% endif %}
</url>
{% endfor %}
</urlset>

Generate the Sitemap

With the controller and Twig template in place, you can now generate the sitemap.xml. To do this, access the sitemap route you defined earlier. For instance, navigate to http://yourdomain.com/sitemap.xml.

Debug session

You can got a 404 error when you visit your sitemap route especially on production.

The solution is to clear the cache.

bin/console cache:clear

Conclusion

You have successfully created a sitemap.xml in Symfony without relying on a specific bundle. The sitemap will assist search engines in crawling and indexing your website, enhancing its visibility and search engine rankings. Remember to keep the sitemap updated and to include all relevant URLs from your website to ensure that search engines can efficiently navigate and display your content in search results.

Stay connected, stay informed, and stay inspired! Today, I invite you to take the next step and follow me. Thank you for being a loyal reader. I appreciate your support. Happy coding ! 😉

--

--

Sd404

Hey there! I'm a passionate web developer, serial reader and tech enthusiast. Follow me on Medium to stay updated with my latest articles. Happy coding! 🚀