# How to Integrate SunSitemap into an Existing PHP Project

> Easily integrate SunSitemap into your PHP project to generate XML sitemaps and update robots.txt. This lightweight pure-PHP class requires no external dependencies. Learn how now.

- Repository: [Mehmet Selcuk Batal/php-sitemap-generator](https://github.com/msbatal/php-sitemap-generator)
- Tags: how-to-guide
- Published: 2026-03-07

---

**SunSitemap is a lightweight, pure-PHP class with zero external dependencies that generates XML sitemaps and updates your [`robots.txt`](https://github.com/msbatal/php-sitemap-generator/blob/main/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`](https://github.com/msbatal/php-sitemap-generator/blob/main/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 for `lastmod`, `changefreq`, and `priority` attributes.
- **`createSitemap()`**: Chunks URLs into protocol-compliant segments, generates XML `<urlset>` documents, optionally produces gzip-compressed versions, and creates a [`sitemap-index.xml`](https://github.com/msbatal/php-sitemap-generator/blob/main/sitemap-index.xml) when multiple files are required.
- **`updateRobots()`**: Automatically generates or appends `Sitemap:` directives to [`robots.txt`](https://github.com/msbatal/php-sitemap-generator/blob/main/robots.txt), pointing to the sitemap index or individual files.
- **Utility methods**: `memoryUsage()` and `showDuration()` 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:

1. **Copy the class file**  
   Place [`SunSitemap.php`](https://github.com/msbatal/php-sitemap-generator/blob/main/SunSitemap.php) from the repository into your project directory (e.g., [`src/SunSitemap.php`](https://github.com/msbatal/php-sitemap-generator/blob/main/src/SunSitemap.php)).

2. **Require the class**  
   Include the file where you need to trigger sitemap generation:

   ```php
   require_once 'src/SunSitemap.php';
   ```

3. **Instantiate the generator**  
   Create an instance with your site configuration:

   ```php
   $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
   );
   ```

4. **Add URLs**  
   Populate the sitemap individually or in bulk:

   ```php
   // 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);
   ```

5. **Generate files**  
   Execute the creation and robots update using method chaining:

   ```php
   $sitemap->createSitemap()->updateRobots();
   ```

6. **Retrieve diagnostics** (Optional)  
   Monitor resource consumption:

   ```php
   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:

```php
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:

```php
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:

```php
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:

```php
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`](https://github.com/msbatal/php-sitemap-generator/blob/main/sitemap-1.xml), [`sitemap-2.xml`](https://github.com/msbatal/php-sitemap-generator/blob/main/sitemap-2.xml)).

**Index Generation**: When multiple files are created, SunSitemap automatically generates a [`sitemap-index.xml`](https://github.com/msbatal/php-sitemap-generator/blob/main/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`](https://github.com/msbatal/php-sitemap-generator/blob/main/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`, `zlib` for optional compression).
- **Integration requires a single file** ([`SunSitemap.php`](https://github.com/msbatal/php-sitemap-generator/blob/main/SunSitemap.php)) and standard `require_once` inclusion.
- **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`](https://github.com/msbatal/php-sitemap-generator/blob/main/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`](https://github.com/msbatal/php-sitemap-generator/blob/main/robots.txt), giving you full control over when and how search engines discover your sitemaps.