SEO & Utilities

PHP XML Sitemap Generator

Build XML sitemaps from a list of trusted canonical URLs using XMLWriter.

Overview

Build XML sitemaps from a list of trusted canonical URLs using XMLWriter.

What this script does

This starter demonstrates the core implementation pattern. Adapt database fields, configuration and error handling to your application.

Source code

<?php
declare(strict_types=1);
function renderSitemap(array $urls): string {
    $xml=new XMLWriter(); $xml->openMemory(); $xml->startDocument('1.0','UTF-8');
    $xml->startElement('urlset'); $xml->writeAttribute('xmlns','http://www.sitemaps.org/schemas/sitemap/0.9');
    foreach ($urls as $item) {
        $loc=(string)($item['loc']??'');
        if (!filter_var($loc,FILTER_VALIDATE_URL) || !in_array(parse_url($loc,PHP_URL_SCHEME),['http','https'],true)) continue;
        $xml->startElement('url'); $xml->writeElement('loc',$loc);
        if (!empty($item['lastmod'])) $xml->writeElement('lastmod',(string)$item['lastmod']);
        $xml->endElement();
    }
    $xml->endElement(); $xml->endDocument(); return $xml->outputMemory();
}

Download starter source: Download PHP XML Sitemap Generator source

Installation and customization

  1. Review the code and required PHP extensions.
  2. Configure database and storage settings outside the public web root where applicable.
  3. Add authorization, rate limiting and logging for public-facing endpoints.
  4. Test valid, invalid and boundary inputs before deployment.

> This is a learning starter, not a complete production application. Apply the security and deployment requirements of your project.