keyboard

Hugo Soltys

Symfony developer

Since 2013

How to make a sitemap file with Symfony

Posted on by Hugo - 701 views - 6 comments


SEO (Search Engine Optimization) is a major point in a website development. If you want your site to stand out from others in search engines results, you have to do some actions that will help you to reach this objective.

A sitemap is one of them. 

In this tutorial, we will learn how to make a sitemap file very easily step by step.


WHAT IS A SITEMAP ?

 

A sitemap is a XML file that list all the URLs of your website. Search engines like Google have robots that browse the web searching for those sitemaps. Once they found them, search engines index in their results all the URLs present in.

Search engines are able to index your URLs without a sitemap, but it will take way longer time.

 

MAKE YOUR OWN SITEMAP WITH SYMFONY

 

In this tutorial, we are considering we have a website called www.mywebsite.com 

On this site, following URLs are available :

  • www.mywebsite.com  (route name : 'mywebsite_homepage')
  • www.mywebsite.com/blog (route name : 'mywebsite_blog')
  • www.mywebsite.com/blog/article-1 (route name : 'mywebsite_article')
  • www.mywebsite.com/blog/article-2 (route name : 'mywebsite_article')

 

ROUTING

 

First of all, we need to create a new route for our sitemap.

#src/WebsiteBundle/Resources/config/routing.yml

mywebsite_sitemap:
    path:    /sitemap.xml
    defaults: { _controller: WebsiteBundle:Website:sitemap }

 

THE CONTROLLER

 

In our controller, we will define a new action that will build an array of all the routes we want to show in our sitemap.

<?php

namespace WebsiteBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;

class WebsiteController extends Controller
{
    public function sitemapAction(Request $request) 
    {
        // We define an array of urls
        $urls = [];
        // We store the hostname of our website
        $hostname = $request->getHost();

        $urls[] = ['loc' => $this->get('router')->generate('mywebsite_homepage'), 'changefreq' => 'weekly', 'priority' => '1.0'];    
        $urls[] = ['loc' => $this->get('router')->generate('mywebsite_blog'), 'changefreq' => 'weekly', 'priority' => '1.0'];

        // Then, we will find all our articles stored in the database
        $articlesRepository = $this->getDoctrine()->getRepository('WebsiteBundle:Article');
        $articles = $articlesRepository->findAll();

        // We loop on them
        foreach ($articles as $article) {
            $urls[] = ['loc' => $this->get('router')->generate('mywebsite_article', ['title' => $article->getTitle()]), 'changefreq' => 'weekly', 'priority' => '1.0'];
        }

        // Once our array is filled, we define the controller response
        $response = new Response();
        $response->headers->set('Content-Type', 'xml');

        return $this->render('WebsiteBundle:Website:sitemap.xml.twig', [
            'urls' => $urls,
            'hostname' => $hostname
        ])
    }
}

 

TWIG TEMPLATE FILE

 

A sitemap have a precise XML structure. For each route, we must specify multiple required informations that I explain lower.

<?xml version="1.0" encoding="UTF-8" ?>
<urlset 
    xmlns="http://sitemaps.org/schemas/sitemap/0.9"
    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>
        {# check if hostname is not already in url #}
        <loc>{% if url.loc|replace({hostname:''}) == url.loc %}http://{{hostname}}{{url.loc}}{% else %}{{url.loc}}{% endif %}</loc>
        {% 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 %}

 

SOME PRECISIONS ABOUT EXISTING SITEMAP PARAMETERS

 

As you must have seen in the above code, a sitemap have some parameters like loc, changefreq or priority.

 

  • Loc means location and must contain the url you want to index
  • Changefreq define the frequency at which the url change
  • Priority define the importance of the url compared to others

 

I hope this tutorial helped you !

Don't hesitate if you have some questions.

 

Hugo.


Hugo Soltys

My name is Hugo, I'm 25 and I'm a Symfony developer since 2013. I love to create websites by myself to learn new technologies or increase my skills.
I love movies, books, music and video games. I also like to drink a few beers with my friends. I'm from Lille (France) and I currently work as Symfony developer at Decathlon since 2016. Before that, I worked as Symfony developer for the IT Room company, in Roubaix, France.