' . PHP_EOL; $sitemap_index .= '' . PHP_EOL; // This array will hold chunks of content $sitemap_files = []; /** * 6) For each keyword: * - Convert spaces → hyphens * - Lowercase the slug (for consistency) * - rawurlencode it * - Assign it to the appropriate chunk (every $max_links_per_sitemap) */ foreach ($keywords as $i => $keyword) { // 6a) Lowercase the keyword, replace spaces with hyphens $lowercased = mb_strtolower($keyword, 'UTF-8'); $slug_candidate = str_replace(' ', '-', $lowercased); // 6b) rawurlencode the slug (Thai characters → %E0…, etc.) $encoded_keyword = rawurlencode($slug_candidate); // 6c) Determine which chunk number this link belongs to $sitemap_num = (int)ceil(($i + 1) / $max_links_per_sitemap); // 6d) If this is the first URL in chunk‐# $sitemap_num, initialize if (!isset($sitemap_files[$sitemap_num])) { $sitemap_files[$sitemap_num] = '' . PHP_EOL; $sitemap_files[$sitemap_num] .= '' . PHP_EOL; } // 6e) Build the full URL and escape for XML $full_url = $base_url . $encoded_keyword; $escaped_url = htmlspecialchars($full_url, ENT_QUOTES, 'UTF-8'); $sitemap_files[$sitemap_num] .= " " . PHP_EOL; $sitemap_files[$sitemap_num] .= " {$escaped_url}" . PHP_EOL; $sitemap_files[$sitemap_num] .= " " . PHP_EOL; } // 7) Close each , write to its own file, and add it to sitemap‐index foreach ($sitemap_files as $num => $content) { $content .= '' . PHP_EOL; // Write chunk file (e.g. sitemap-1.xml, sitemap-2.xml, …) $chunk_filename = "{$sitemap_name}-{$num}.xml"; $absolute_path = $script_dir . DIRECTORY_SEPARATOR . $chunk_filename; if (false === file_put_contents($absolute_path, $content)) { die("❌ Failed to write {$absolute_path}. Check permissions."); } // In the sitemap‐index, point to the public URL for this chunk $index_loc = htmlspecialchars($domain_url . $chunk_filename, ENT_QUOTES, 'UTF-8'); $sitemap_index .= " " . PHP_EOL; $sitemap_index .= " {$index_loc}" . PHP_EOL; $sitemap_index .= " " . PHP_EOL; } // 8) Finalize and write sitemap‐index.xml $sitemap_index .= '' . PHP_EOL; $index_filename = $script_dir . DIRECTORY_SEPARATOR . 'sitemap-index.xml'; if (false === file_put_contents($index_filename, $sitemap_index)) { die("❌ Failed to write {$index_filename}. Check permissions."); } // 9) Success message (with a real newline) echo "sitemap-index.xml"; ?>