How the addUrl() Method Handles Arrays of URLs in PHP Sitemap Generator

The addUrl() method processes arrays of URLs by detecting the array type, iterating through each element, and recursively calling itself to handle individual URL entries with their optional metadata.

In the msbatal/php-sitemap-generator repository, the addUrl() method in SunSitemap.php provides a flexible interface for batching sitemap entries. While it supports adding URLs one at a time with individual parameters, it also accepts a nested array structure to process multiple URLs in a single call, as implemented in lines 48-57 of the source file.

Array Detection and Iteration Logic

According to the source code in SunSitemap.php, the method first checks if the input is an array using is_array($urls). When this condition evaluates to true, the method enters a dedicated processing branch rather than treating the input as a single URL string.

The method then loops through the outer array using foreach ($urls as $url). Each iteration expects $url to be a sub-array containing up to four indexed elements representing the URL properties.

Recursive Single-URL Processing

For each sub-array encountered, addUrl() invokes itself recursively. This design reuses the existing single-URL validation and storage logic implemented in the same method. The recursive call extracts array elements using isset() checks to handle optional parameters safely:

$this->addUrl(
    isset($url[0]) ? $url[0] : null,
    isset($url[1]) ? $url[1] : null,
    isset($url[2]) ? $url[2] : null,
    isset($url[3]) ? $url[3] : null
);

This recursion continues until all array elements are processed, with each valid URL stored in the internal $this->urls collection.

Expected Array Structure

When passing an array to addUrl(), each inner array must follow a specific index-based format:

  • Index 0: The URL path (relative to baseUrl) — Required
  • Index 1: The lastmod date in ISO-8601 format — Optional
  • Index 2: The changefreq value (always, hourly, daily, weekly, monthly, yearly, never) — Optional
  • Index 3: The priority value as a float between 0.0 and 1.0 — Optional

If optional indices are omitted or set to null, the method skips setting those attributes during the recursive call.

Practical Implementation Example

The following example demonstrates both individual and batch URL addition using the SunSitemap class:

<?php
require 'SunSitemap.php';

// Initialize the sitemap generator
$sitemap = new SunSitemap([
    'baseUrl' => 'https://example.com',
    'sitemapFile' => 'sitemap.xml'
]);

// Method 1: Adding URLs individually
$sitemap->addUrl('index.php', date('c'), 'daily', '1');
$sitemap->addUrl('about/contact.php', date('c'), 'monthly', '0.8');

// Method 2: Adding multiple URLs via array
$urls = [
    // Minimum required data: URL path only
    ['products/item1.php'],
    
    // Complete entry with all metadata
    ['products/item2.php', '2024-01-15', 'weekly', '0.9'],
    
    // Partial entry with selective metadata (nulls are ignored)
    ['blog/post123.php', null, 'daily']
];

// Single call processes the entire array
$sitemap->addUrl($urls);

// Generate the sitemap files
$sitemap->createSitemap();
?>

After processing, all URLs reside in $this->urls, ready for createSitemap() to generate the final XML files.

Summary

  • The addUrl() method in SunSitemap.php detects arrays using is_array() and processes them separately from single URLs.
  • It iterates through the outer array and recursively calls itself for each sub-array to leverage existing validation logic.
  • Each sub-array must contain the URL path at index 0, with optional lastmod, changefreq, and priority values at indices 1-3.
  • Omitted optional values are handled gracefully through isset() checks in the recursive invocation.
  • All processed URLs accumulate in the $this->urls property for subsequent sitemap generation.

Frequently Asked Questions

What happens if I omit optional metadata in the URL array?

The method uses isset() checks when making recursive calls. If you omit indices 1-3 (or set them to null), the method passes null for those parameters, and the single-URL processing logic ignores unset values rather than adding empty XML tags.

Can I mix single URLs and arrays in the same addUrl() call?

No, the method determines the processing branch based on the type of the first argument. If you pass a string, it processes a single URL. If you pass an array, it expects every element to be a sub-array representing a URL entry. To add URLs individually after a batch operation, make separate method calls.

Where does the actual URL validation occur in the source code?

While the array-handling logic resides in lines 48-57 of SunSitemap.php, the actual validation, construction of the $urlArray, and storage into $this->urls occurs in the single-URL processing branch that executes when is_array($urls) returns false. The recursive call ensures each array element eventually hits this validation logic.

Is there a performance benefit to using arrays versus multiple single calls?

Both approaches ultimately execute the same validation and storage logic. However, using the array syntax reduces PHP method call overhead from your application code and produces cleaner, more maintainable code when adding large batches of URLs to the sitemap.

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:

Share the following with your agent to get started:
curl -s "https://instagit.com/install.md"

Works with
Claude Codex Cursor VS Code OpenClaw Any MCP Client

Maintain an open-source project? Get it listed too →