How to Integrate SunSitemap into an Existing PHP Project
SunSitemap is a lightweight, pure-PHP class with zero external dependencies that generates XML sitemaps and updates your robots.txt file by simply including the class file and calling its public API methods.
SunSitemap, available in the msbatal/php-sitemap-generator repository, provides a self-contained solution for creating search engine-friendly XML sitemaps. Because the implementation relies solely on built-in PHP extensions like SimpleXMLElement and zlib, you can integrate it into any legacy or modern PHP codebase without Composer or dependency management overhead.
Core Architecture and Components
The SunSitemap Class Structure
The generator logic resides entirely in SunSitemap.php and consists of five primary components:
- Constructor: Accepts configuration for
$baseUrl,$relPath,$maxUrl, and$createZip, automatically resolving the document root for file output paths. addUrl(): Appends single URLs or arrays to an internal collection, accepting optional parameters forlastmod,changefreq, andpriorityattributes.createSitemap(): Chunks URLs into protocol-compliant segments, generates XML<urlset>documents, optionally produces gzip-compressed versions, and creates asitemap-index.xmlwhen multiple files are required.updateRobots(): Automatically generates or appendsSitemap:directives torobots.txt, pointing to the sitemap index or individual files.- Utility methods:
memoryUsage()andshowDuration()provide performance diagnostics after generation.
Dependency Requirements
The class requires only standard PHP extensions. It uses SimpleXMLElement for XML construction and gzopen for compression. If you enable $createZip, the generator verifies that the zlib output handler is available; otherwise, it throws an exception during execution.
Step-by-Step Integration Guide
Follow these steps to add SunSitemap to your existing project:
-
Copy the class file
PlaceSunSitemap.phpfrom the repository into your project directory (e.g.,src/SunSitemap.php). -
Require the class
Include the file where you need to trigger sitemap generation:require_once 'src/SunSitemap.php'; -
Instantiate the generator
Create an instance with your site configuration:$sitemap = new SunSitemap( $baseUrl = 'https://example.com', // Base URL (defaults to current host if omitted) $relPath = 'public/sitemap', // Relative directory for output $maxUrl = 10000, // URLs per file (defaults to 50,000) $createZip = true // Enable .gz compression ); -
Add URLs
Populate the sitemap individually or in bulk:// Single URL $sitemap->addUrl('index.php', date('c'), 'daily', '1.0'); // Array of URLs $urls = [ ['about.php', date('c'), 'monthly', '0.8'], ['contact.php', date('c'), 'yearly', '0.4'] ]; $sitemap->addUrl($urls); -
Generate files
Execute the creation and robots update using method chaining:$sitemap->createSitemap()->updateRobots(); -
Retrieve diagnostics (Optional)
Monitor resource consumption:echo 'Peak Memory: ' . $sitemap->memoryUsage() . ' MB'; echo 'Execution Time: ' . $sitemap->showDuration() . ' s';
Practical Code Examples
Minimal Integration for Small Sites
For straightforward implementations with default settings:
require_once 'src/SunSitemap.php';
$sitemap = new SunSitemap('https://example.com', 'public/sitemap');
$sitemap->addUrl('index.php', date('c'), 'daily', '1.0');
$sitemap->addUrl('products.php', date('c'), 'weekly', '0.9');
$sitemap->createSitemap()->updateRobots();
High-Volume Site with Gzip Compression
When managing larger URL sets with compression:
require_once 'src/SunSitemap.php';
$sitemap = new SunSitemap(
'https://example.com',
'public/sitemap',
20000, // Split into 20,000-URL chunks
true // Create .gz files
);
// Add thousands of URLs...
$sitemap->addUrl('category/item-1.php', date('c'), 'weekly', '0.8');
$sitemap->createSitemap()->updateRobots();
Batch URL Processing
Insert multiple URLs efficiently using arrays:
require_once 'src/SunSitemap.php';
$pages = [
['index.php', date('c'), 'daily', '1.0'],
['blog/post-1.php', date('c'), 'weekly', '0.9'],
['blog/post-2.php', date('c'), 'weekly', '0.9'],
];
$sitemap = new SunSitemap('https://example.com', 'public/sitemap');
$sitemap->addUrl($pages);
$sitemap->createSitemap()->updateRobots();
Separate Method Calls for Custom Logic
When you need to execute steps conditionally:
require_once 'src/SunSitemap.php';
$sitemap = new SunSitemap('https://example.com', 'public/sitemap');
$sitemap->addUrl('page1.php');
$sitemap->addUrl('page2.php');
$sitemap->createSitemap(); // Write XML files
if ($shouldUpdateRobots) {
$sitemap->updateRobots();
}
How File Generation Works
Path Resolution: When you provide $relPath, the constructor sanitizes the string and concatenates it with $_SERVER['DOCUMENT_ROOT'] to determine the absolute write location for all generated files.
Protocol Compliance: The createSitemap() method automatically chunks your URL collection into segments respecting the 50,000-URL limit imposed by the sitemap protocol. If your dataset exceeds $maxUrl, the generator produces multiple numbered sitemap files (e.g., sitemap-1.xml, sitemap-2.xml).
Index Generation: When multiple files are created, SunSitemap automatically generates a sitemap-index.xml containing <sitemap> entries that reference each chunk. If gzip is enabled, the index points to the compressed versions (*.xml.gz).
Robots Integration: The updateRobots() method writes the appropriate Sitemap: directive to robots.txt at the document root. It intelligently points to the sitemap index when one exists, or to the single sitemap file (and its gzipped counterpart) when applicable.
Summary
- SunSitemap requires no external dependencies — only core PHP extensions (
SimpleXMLElement,zlibfor optional compression). - Integration requires a single file (
SunSitemap.php) and standardrequire_onceinclusion. - Configuration happens through the constructor, which accepts base URL, output path, URL limits, and compression preferences.
- URL addition supports both single and batch operations via the flexible
addUrl()method. - Method chaining enables concise execution:
createSitemap()->updateRobots(). - Automatic chunking ensures compliance with the 50,000-URL protocol limit while generating proper sitemap indexes.
- Robots.txt updates are handled automatically, ensuring search engine discoverability without manual file editing.
Frequently Asked Questions
Does SunSitemap require Composer or external dependencies?
No. SunSitemap is a single-file, pure-PHP class that uses only built-in extensions. You can include it directly with require_once without initializing Composer or managing vendor directories, making it ideal for legacy projects or lightweight applications.
What is the maximum number of URLs SunSitemap can handle?
The class handles unlimited URLs by automatically splitting them into multiple files. While each individual sitemap file respects the 50,000-URL limit defined by the sitemap protocol, the generator creates a sitemap-index.xml to reference additional files, allowing you to index millions of pages across your site.
How does SunSitemap determine where to write the generated files?
The constructor resolves the absolute path by combining $_SERVER['DOCUMENT_ROOT'] with your provided $relPath parameter. This ensures files are written to the correct server location regardless of where your execution script resides in the project structure.
Can I generate sitemaps without updating the robots.txt file?
Yes. While the examples show createSitemap()->updateRobots() chaining, these are independent methods. You can call $sitemap->createSitemap() alone to generate the XML files without modifying robots.txt, giving you full control over when and how search engines discover your sitemaps.
Have a question about this repo?
These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:
curl -s "https://instagit.com/install.md" Maintain an open-source project? Get it listed too →