Dynamic Sitemap with Slim 3 Framework

... by Bittle in Slim 3 Framework February 24, 2019

What is a Sitemap?

Think about your website as a house, and each link inside your website as a room. The Sitemap is a blueprint of your website and Google is the inspector. We need to let Google know what links are important inside the website since pages are also ranked (not just websites).


So Why is This Important?

We want to rank higher in search engines (Search Engine Optimization) since this will result in higher traffic and more revenue.

Sitemaps are important if

  • You have pages that are dynamically created
  • Your site is extremely large with multiple pages
  • Your site is just newly developed

It doesn't hurt to have a Sitemap even if you believe to not need it.


Using Slim 3 Framework to create Dynamic Sitemap

There are several ways to create a Sitemap, such as creating a .php file that converts to .xml, but we will use slim and set the content type to xml - to avoid rerouting and renaming. First we need to list all the routes that have been registered in $app. To do this execute the following code inside a route:

<?php
foreach ($this->router->getRoutes() as $r) {
  echo $r->getPattern();
  echo "<br/>";
}

Chose the urls that have no child routes. For Kode Central we have the following routes:

<?php
$urls = ["/","/search","/contact","/about-us","/faq","/all-pages"];

For other routes that have children routes that change dynamically we will make a Sitemap.php view and render them. Create an Slim App object and render Sitemap.php and pass the desired variables:

<?php
// composer autoload file
require '../vendor/autoload.php';

// propels config file to connect to database
require '../data/generated-conf/config.php';

$app = new \Slim\App(["settings" => ["displayErrorDetails" => true]]);

$container = $app->getContainer();

// directory where views are located
$container['view'] = new \Slim\Views\PhpRenderer("../app/views/");

$app->get('/sitemap.xml', function ($request, $response, $args) {
    // to render xml
    $response = $response->withHeader('Content-type', 'application/xml');

    // base urls
    $urls = ["/","/search","/contact","/about-us","/faq","/all-pages"];

    // variables that have children links
    // ex: post/{post-link}
    $posts = \PostQuery::create()->find();
    $users = \UserQuery::create()->find();
    $libs = \LibraryQuery::create()->find();
    return $this->view->render(
          $response,
          'sitemap.php',
          ['router'=>$this->router, 'urls'=>$urls, 'posts'=>$posts, 'users'=>$users, 'libs'=>$libs]
      );
});

$app->run();

Then output in xml format (sitemap.php view in app/view directory)

<?php
$base_url = 'https://kodecentral.com';

// basic xml header info
echo '<?xml version="1.0" encoding="UTF-8"?>'.PHP_EOL.
'<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">' . PHP_EOL;

foreach ($urls as $url) {
    echo '<url>' . PHP_EOL;
    echo '<loc>'.$base_url.$url.'</loc>' . PHP_EOL;
    echo '<changefreq>daily</changefreq>' . PHP_EOL;
    echo '</url>' . PHP_EOL;
}

// posts
foreach ($posts as $post) {
    echo '<url>' . PHP_EOL;
    echo '<loc>'.$base_url.'/post/'. $post->getHyperlink() .'</loc>' . PHP_EOL;
    echo '<changefreq>daily</changefreq>' . PHP_EOL;
    echo '</url>' . PHP_EOL;
}

// users
foreach ($users as $user) {
    echo '<url>' . PHP_EOL;
    echo '<loc>'.$base_url.'/profile/'. urlencode($user->getUsername()) .'</loc>' . PHP_EOL;
    echo '<changefreq>daily</changefreq>' . PHP_EOL;
    echo '</url>' . PHP_EOL;
}

// libraries
foreach ($libs as $lib) {
    echo '<url>' . PHP_EOL;
    echo '<loc>'.$base_url.'/lib/'. urlencode($lib->getName()) .'</loc>' . PHP_EOL;
    echo '<changefreq>daily</changefreq>' . PHP_EOL;
    echo '</url>' . PHP_EOL;
}

// close tag
echo '</urlset>' . PHP_EOL;

Tags

  • <urlset> : Encapsulates the file and references the current protocol standard.
  • <url> : Parent tag for each URL entry. The remaining tags are children of this tag.
  • <loc> : URL of the page. This URL must begin with the protocol (such as http) and end with a trailing slash, if your web server requires it. This value must be less than 2,048 characters.
  • <changefreq> : How frequently the page is likely to change. This value provides general information to search engines and may not correlate exactly to how often they crawl the page.
  • More information at sitemap.org

You can see the Sitemap at kodecentral.com/sitemap.xml


Clarifications:

Composer is used to install Slim, Slim Php View, and Propel ORM.

{
  "require": {
    "propel/propel": "~2.0@dev",
    "slim/slim": "^3.9",
    "slim/php-view": "^2.2"
  },
  "autoload": {
    "classmap": [
      "data/models/"
    ],
    "psr-4":{
      "app\\": "app/"
    }
  }
}

And there you go! Go into your Google Search Console and link your new Sitemap.

Comments (0)

Search Here