Back to Homepage

Transform Your Spatie Sitemap with XSL

8 min read

Tags:

Spatie Laravel
Transform Your Spatie Sitemap with XSL

Are you looking to take your website's sitemap to the next level? With Stylish XSL, you can transform a Spatie Sitemap into an engaging visual representation of your website. This blog post will provide an overview of what a Spatie Sitemap with XSL is the best way to customize it, and how to set up XSL templates. Plus, you'll get examples of stylish XSL transformations and additional resources for further customization. Read on to learn more about transforming your Spatie Sitemap with Stylish XSL and don't forget to check out our other email tutorials for more insights!

Overview of spatie sitemap

A spatie sitemap is an XML file that lists the URLs for a website, making it easier for search engines to crawl and index a website’s content. It contains important information about how a website should be crawled and indexed, including the frequency of updates, how often pages are changed, and when they were last modified. Spatie sitemaps provide structure to websites, helping search engine crawlers more efficiently navigate through them

Why use XSL to transform your sitemap

XSL, or Extensible Stylesheet Language, is an ideal choice for transforming a Spatie Sitemap into a stylish and engaging visual representation. XSL provides an efficient way to transform structured data into something more appealing to the eye, while also providing a wide range of features that can be used to customize the look and feel of the sitemap.

Not only does XSL help beautify your sitemap, it can also help improve its search engine optimization (SEO). By making sure your sitemap is properly formatted with relevant keywords and meta descriptions, your website will have better chances of being ranked highly in search engines. Additionally, using XSL templates makes it easy to track changes in your sitemap over time for better accuracy.

XSL also offers flexibility when it comes to designing the layout of your sitemap. Unlike static HTML documents that require extensive coding knowledge to create custom layouts, XSL allows you to quickly create different types of layouts tailored specifically for different use cases. From simple grids and lists to complex forms and charts, XSL can help you create stunning visuals without breaking a sweat.

Installation

First, install the package via composer:

composer require spatie/laravel-sitemap

Step 2: Create a new class, say MySitemap, extending Spatie\Sitemap\Sitemap and add a method to set the stylesheet URL, and override the render method to include the stylesheet processing instruction.

<?php

namespace App\Services;

use Spatie\Sitemap\Sitemap;
use Spatie\Sitemap\Tags\Url;

class MySitemap extends Sitemap
{
    protected ?string $stylesheet = null;

    public function setStylesheet(string $stylesheet): self
    {
        $this->stylesheet = $stylesheet;

        return $this;
    }

    public function render(): string
    {
        $xml = parent::render();

        if ($this->stylesheet) {
            $stylesheetInstruction = '<?xml-stylesheet type="text/xsl" href="' . $this->stylesheet . '"?>';
            $xml = str_replace('<?xml version="1.0" encoding="UTF-8"?>', '<?xml version="1.0" encoding="UTF-8"?>' . $stylesheetInstruction, $xml);
        }

        return $xml;
    }
}

Step 3: Create your SitemapService to use MySitemap instead of Spatie\Sitemap\Sitemap.

<?php
namespace App\Services;

use Spatie\Sitemap\Sitemap;
use Spatie\Sitemap\Tags\Url;
use App\Models\Article;
use App\Services\MySitemap;

class SitemapService
{
    public function generate()
    {
        $sitemap = MySitemap::create()
            ->setStylesheet(url('sitemap.xsl'))
            ->add(Url::create('/')->setPriority(0.1));

        $this->appendArticles($sitemap);

        return $sitemap;
    }

    protected function appendArticles(Sitemap $sitemap)
    {
        Article::all()->each(function (Article $article) use ($sitemap) {
            $sitemap->add(
                Url::create("/{$article->slug}")
                    ->setLastModificationDate($article->updated_at)
                    ->setChangeFrequency(Url::CHANGE_FREQUENCY_WEEKLY)
                    ->setPriority(0.8)
            );
        });
    }

}

Step 4: Create Sitemap.xsl in public directory and paste the below code

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="2.0"
                xmlns:html="http://www.w3.org/TR/REC-html40"
                xmlns:image="http://www.google.com/schemas/sitemap-image/1.1"
                xmlns:sitemap="http://www.sitemaps.org/schemas/sitemap/0.9"
                xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="html" version="1.0" encoding="UTF-8" indent="yes"/>
    <xsl:template match="/">
        <html xmlns="http://www.w3.org/1999/xhtml">
            <head>
                <title>XML Sitemap</title>
                <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
                <style type="text/css">
                    body {
                        font-family: Helvetica, Arial, sans-serif;
                        font-size: 13px;
                        color: #545353;
                    }
                    table {
                        border: none;
                        border-collapse: collapse;
                    }
                    #sitemap tr:nth-child(odd) td {
                        background-color: #eee !important;
                    }
                    #sitemap tbody tr:hover td {
                        background-color: #ccc;
                    }
                    #sitemap tbody tr:hover td, #sitemap tbody tr:hover td a {
                        color: #000;
                    }
                    #content {
                        margin: 0 auto;
                        width: 1000px;
                    }
                    .expl {
                        margin: 18px 3px;
                        line-height: 1.2em;
                    }
                    .expl a {
                        color: #da3114;
                        font-weight: 600;
                    }
                    .expl a:visited {
                        color: #da3114;
                    }
                    a {
                        color: #000;
                        text-decoration: none;
                    }
                    a:visited {
                        color: #777;
                    }
                    a:hover {
                        text-decoration: underline;
                    }
                    td {
                        font-size:11px;
                    }
                    th {
                        text-align:left;
                        padding-right:30px;
                        font-size:11px;
                    }
                    thead th {
                        border-bottom: 1px solid #000;
                    }
                </style>
            </head>
            <body>
                <div id="content">
                    <h1>XML Sitemap</h1>
                    <p class="expl">
                        This is an XML Sitemap, meant for consumption by search engines.<br/>
                        You can find more information about XML sitemaps on <a href="http://sitemaps.org" target="_blank" rel="noopener noreferrer">sitemaps.org</a>.
                    </p>

                    <hr/>
                    <xsl:if test="count(sitemap:sitemapindex/sitemap:sitemap) &gt; 0">
                        <p class="expl">
                            This XML Sitemap Index file contains <xsl:value-of select="count(sitemap:sitemapindex/sitemap:sitemap)"/> sitemaps.
                        </p>
                        <table id="sitemap" cellpadding="3">
                            <thead>
                                <tr>
                                    <th width="75%">Sitemap</th>
                                    <th width="25%">Last Modified</th>
                                </tr>
                            </thead>
                            <tbody>
                                <xsl:for-each select="sitemap:sitemapindex/sitemap:sitemap">
                                    <xsl:variable name="sitemapURL">
                                        <xsl:value-of select="sitemap:loc"/>
                                    </xsl:variable>
                                    <tr>
                                        <td>
                                            <a href="{$sitemapURL}"><xsl:value-of select="sitemap:loc"/></a>
                                        </td>
                                        <td>
                                            <xsl:value-of select="concat(substring(sitemap:lastmod,0,11),concat(' ', substring(sitemap:lastmod,12,5)),concat(' ', substring(sitemap:lastmod,20,6)))"/>
                                        </td>
                                    </tr>
                                </xsl:for-each>
                            </tbody>
                        </table>
                    </xsl:if>
                    <xsl:if test="count(sitemap:sitemapindex/sitemap:sitemap) &lt; 1">
                        <p class="expl">
                            This XML Sitemap contains <xsl:value-of select="count(sitemap:urlset/sitemap:url)"/> URLs.
                        </p>
                        <table id="sitemap" cellpadding="3">
                            <thead>
                                <tr>
                                    <th width="80%">URL</th>
                                    <th width="5%">Priority</th>
                                    <th title="Last Modification Time" width="15%">Last Mod.</th>
                                </tr>
                            </thead>
                            <tbody>
                                <xsl:variable name="lower" select="'abcdefghijklmnopqrstuvwxyz'"/>
                                <xsl:variable name="upper" select="'ABCDEFGHIJKLMNOPQRSTUVWXYZ'"/>
                                <xsl:for-each select="sitemap:urlset/sitemap:url">
                                    <tr>
                                        <td>
                                            <xsl:variable name="itemURL">
                                                <xsl:value-of select="sitemap:loc"/>
                                            </xsl:variable>
                                            <a href="{$itemURL}">
                                                <xsl:value-of select="sitemap:loc"/>
                                            </a>
                                        </td>
                                        <td>
                                            <xsl:value-of select="sitemap:priority"/>
                                        </td>
                                        <td>
                                            <xsl:value-of select="concat(substring(sitemap:lastmod,0,11),concat(' ', substring(sitemap:lastmod,12,5)),concat(' ', substring(sitemap:lastmod,20,6)))"/>
                                        </td>
                                    </tr>
                                </xsl:for-each>
                            </tbody>
                        </table>
                    </xsl:if>
                </div>
            </body>
        </html>
    </xsl:template>
</xsl:stylesheet>

Step 5: Now the final step, Create a SitemapController and put below code, I even added cache block to save server resources from bots.

<?php

namespace App\Http\Controllers;

use App\Services\SitemapService;
use Illuminate\Support\Facades\Cache;

class SitemapController extends Controller
{
    protected SitemapService $sitemapService;

    public function __construct(SitemapService $sitemapService)
    {
        $this->sitemapService = $sitemapService;
    }

    public function generate()
    {
        $sitemap = Cache::remember('sitemap', now()->addHours(24), function () {
            return $this->sitemapService->generate();
        });
        return $sitemap->toResponse(request());
    }
}

Once these steps have been followed, you can start styling your sitemap using CSS styles such as bold fonts, highlight colors, drop shadows and rounded corners - all of which will help make it look more attractive and eye-catching. You may also want to consider adding search bars or tabs at the top of the page for simpler navigation. These features not only enhance user experience but also boost SEO performance since search engines understand data presented in a structured format much better than unstructured text documents like HTML pages or plain text files.

Final Look of the Sitemap.

Screenshot 2023-10-25 at 1.27.30 PM

Conclusion

Finally, there are a number of online resources available that provide tips and tricks on how best to use XSL for sitemap customization. All of this information serves to make it easier for designers and developers alike to create stylish visual representations of their websites using Spatie Sitemaps with XSL.

Follow @LaravelSage on X → Follow @LaravelSage on Facebook →
Aniket Singh

Aniket Singh

View All Articles

Full-stack developer with a knack for Merging creativity with technical expertise for standout solutions.

Related Articles

data_forget Helper for Laravel

data_forget Helper for Laravel

Since Laravel version 10.15, there is a new utility function called data_forget that allows you to remove keys from an array or object using a "dot" notation.

Laravel Tenant Application with Tenancy

Laravel Tenant Application with Tenancy

You can make your Laravel app multi-tenant using the Tenancy for Laravel Tenant package. This tenancy package lets you make any Laravel application multi-tenant without rewriting it.

Top Laravel Packages for Building Powerful Applications

Top Laravel Packages for Building Powerful Applications

Are you ready to take your Laravel skills to the next level and build extraordinary applications? Look no further! In this blog post, we will unveil a treasure trove of top packages that will revolutionize your development process.

Subscribe for 20+ new Laravel tutorials every week

You can unsubscribe at any time. You'll also get -20% off my courses!

© 2024

 

Laravel Sage

   |    Privacy Policy