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
- Review the code and required PHP extensions.
- Configure database and storage settings outside the public web root where applicable.
- Add authorization, rate limiting and logging for public-facing endpoints.
- 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.