Skip to content
← Back to Snippets
Code

Sitemap Batch URL Planner

Splits sitemap URLs into bounded XML sitemap batches with stable filenames and priority metadata.

Purpose

Splits sitemap URLs into bounded XML sitemap batches with stable filenames and priority metadata.

Snippet details

ContextSeoLevelAdvancedCopy-and-paste statusMarked safe after review.

Categories

  • Security

Code

<?php

/*
 * Copyright (c) 2026 Jeffery L. Paris <jparis@phpog.com>.
 * Free for personal and internal use. Paid project use requires visible credit
 * to Jeffery L. Paris. Corporate use requires a paid license fee unless a
 * separate written license states otherwise.
 */

/**
 * Sitemap Batch URL Planner.
 *
 * Purpose:
 * Splits sitemap URLs into bounded XML sitemap batches with stable filenames and priority metadata.
 *
 * @param array $url_rows URL rows containing loc, priority, and updated values.
 * @param int $batch_limit Maximum URLs per sitemap file.
 * @return array Sitemap batch plan.
 */
function ogSnippetSitemapBatchUrlPlanner(array $url_rows, int $batch_limit): array {
	if ($batch_limit < 1) {
		$batch_limit = 50000;
	}

	$batches = array();
	$current_batch = array();
	$batch_index = 1;

	foreach ($url_rows as $url_row) {
		$location = '';
		if (isset($url_row['loc'])) {
			$location = trim((string) $url_row['loc']);
		}

		if ($location === '') {
			continue;
		}

		$priority = '0.5';
		if (isset($url_row['priority'])) {
			$priority = (string) $url_row['priority'];
		}

		$lastmod = date('Y-m-d');
		if (isset($url_row['updated'])) {
			$lastmod = (string) $url_row['updated'];
		}

		$current_batch[] = array(
			'loc' => $location,
			'priority' => $priority,
			'lastmod' => $lastmod
		);

		if (count($current_batch) >= $batch_limit) {
			$batches[] = array(
				'filename' => 'sitemap-'.$batch_index.'.xml',
				'urls' => $current_batch
			);
			$current_batch = array();
			$batch_index++;
		}
	}

	if (count($current_batch) > 0) {
		$batches[] = array(
			'filename' => 'sitemap-'.$batch_index.'.xml',
			'urls' => $current_batch
		);
	}

	return $batches;
}

$stargate_urls = array(
	array('loc' => '//example.com/chevron-status', 'priority' => '0.8', 'updated' => '2026-07-02'),
	array('loc' => '//example.com/iris-protocol', 'priority' => '0.7', 'updated' => '2026-07-02'),
	array('loc' => '//example.com/alpha-site', 'priority' => '0.6', 'updated' => '2026-07-01')
);

$sitemap_plan = ogSnippetSitemapBatchUrlPlanner($stargate_urls, 2);
echo 'Sitemap files planned: '.count($sitemap_plan);