Sitemap Index Builder
Creates sitemap index entries when URL count exceeds file limits.
Function signature
ogBuildSitemapIndex(sitemaps = array(), options = array())
Categories
- APIs and Webhooks
Parameters
sitemapsSitemap file rows with loc and optional lastmod values.optionsIndex options including max_sitemaps. Recognized keys: `max_sitemaps`.Return value
Short public-safe status message.
- sitemaps
- sitemap_count
- warnings
Compatibility
Existing function name and call order preserved; metadata signature corrected to source.
Minimum PHP version: 7.4
Security notes
Validate request method, identity, permissions, policy arrays, URLs, signatures, and caller-owned allowlists before use; keep secrets and internal paths out of public output.
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.
*/
/**
* Creates sitemap index entries when URL count exceeds file limits.
*
* The helper prepares sitemap index data only. XML rendering and escaping belong in the output layer.
*
* @param array $sitemaps Sitemap file rows with loc and optional lastmod values.
* @param array $options Index options including max_sitemaps.
* @return array Sitemap index data.
*/
function ogBuildSitemapIndex($sitemaps = array(), $options = array()) {
$result = array(
'success' => false,
'message' => '',
'data' => array()
);
if (!is_array($sitemaps)) {
$result['message'] = 'Sitemap rows must be an array.';
return $result;
}
if (!is_array($options)) {
$options = array();
}
$max_sitemaps = 50000;
if (!empty($options['max_sitemaps'])) {
$max_sitemaps = (int)$options['max_sitemaps'];
}
if ($max_sitemaps < 1 || $max_sitemaps > 50000) {
$max_sitemaps = 50000;
}
$index_rows = array();
$warnings = array();
foreach ($sitemaps as $index => $sitemap) {
if (!is_array($sitemap)) {
$warnings[] = 'Row ' . $index . ' skipped because it is not an array.';
continue;
}
$loc = '';
if (!empty($sitemap['loc'])) {
$loc = trim((string)$sitemap['loc']);
}
if (empty($loc)) {
$warnings[] = 'Row ' . $index . ' skipped because loc is missing.';
continue;
}
if (stripos($loc, 'http://') === 0 || stripos($loc, 'https://www.') === 0 || stripos($loc, '//www.') === 0) {
$warnings[] = 'Row ' . $index . ' skipped because URL violates canonical URL policy.';
continue;
}
$lastmod = gmdate('Y-m-d');
if (!empty($sitemap['lastmod'])) {
$time = strtotime((string)$sitemap['lastmod']);
if (!empty($time)) {
$lastmod = gmdate('Y-m-d', $time);
}
}
$index_rows[] = array('loc' => $loc, 'lastmod' => $lastmod);
if (count($index_rows) >= $max_sitemaps) {
break;
}
}
$result['success'] = true;
$result['message'] = 'Sitemap index built.';
$result['data'] = array(
'sitemaps' => $index_rows,
'sitemap_count' => count($index_rows),
'warnings' => $warnings
);
return $result;
}