sitemap.xml generator UPDATED
1 posts by 1 authors in: Forums > CMS Builder
Last Post: Tuesday at 2:06am (RSS)
By zaba - Tuesday at 2:06am
A while back I created a script to scan your permalinks database and generate an xml sitemap for you. I have done a few revisions with the help of claude.ai to make it more useful and you can run it from your own site to generate a sitemap for your customers (that's if your customers site allows access to the database), if not you can upload it to theirs.
This script will generate a sitemap.xml using permalinks from the cmsb__permalinks table where old=0. After generation, you can choose to replace the existing sitemap.xml in your root directory, download it to your computer, or view it in your browser.
Note it assumes you have use cmsb as your database table prefix.
<?php
// Start session to store sitemap content
session_start();
// Handle actions
if (isset($_GET['action']) && isset($_SESSION['sitemap_content'])) {
switch ($_GET['action']) {
case 'download':
header('Content-Type: application/xml');
header('Content-Disposition: attachment; filename="sitemap.xml"');
header('Content-Length: ' . strlen($_SESSION['sitemap_content']));
echo $_SESSION['sitemap_content'];
exit;
case 'view':
header('Content-Type: text/plain');
echo $_SESSION['sitemap_content'];
exit;
case 'replace':
if (file_put_contents($_SERVER['DOCUMENT_ROOT'] . '/sitemap.xml', $_SESSION['sitemap_content']) === false) {
$error = 'Failed to write sitemap.xml to root directory';
} else {
$replace_success = 'Sitemap.xml has been successfully replaced in the root directory!';
}
break;
}
}
// Function to generate the sitemap XML
function generateSitemap($baseUrl, $urls) {
$sitemap = '<?xml version="1.0" encoding="UTF-8"?>' . PHP_EOL;
$sitemap .= '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">' . PHP_EOL;
foreach ($urls as $url) {
// Ensure there are no leading/trailing slashes in the URL
$trimmedUrl = trim($url, '/');
$fullUrl = $baseUrl . '/' . $trimmedUrl . '/';
$sitemap .= ' <url>' . PHP_EOL;
$sitemap .= ' <loc>' . htmlspecialchars($fullUrl) . '</loc>' . PHP_EOL;
$sitemap .= ' <lastmod>' . date('Y-m-d') . '</lastmod>' . PHP_EOL;
$sitemap .= ' <changefreq>monthly</changefreq>' . PHP_EOL;
$sitemap .= ' <priority>0.8</priority>' . PHP_EOL;
$sitemap .= ' </url>' . PHP_EOL;
}
$sitemap .= '</urlset>' . PHP_EOL;
return $sitemap;
}
// Check if the script is accessed via a browser
if (php_sapi_name() !== 'cli' && isset($_SERVER['REQUEST_METHOD'])) {
// Check if form has been submitted
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['generate_sitemap'])) {
// Get form data
$baseUrl = rtrim($_POST['base_url'], '/'); // Remove trailing slash
$dbHost = $_POST['db_host'];
$dbName = $_POST['db_name'];
$dbUsername = $_POST['db_username'];
$dbPassword = $_POST['db_password'];
// Validate required fields
if (empty($baseUrl) || empty($dbHost) || empty($dbName) || empty($dbUsername)) {
$error = "Please fill in all required fields.";
} else {
// Database connection
$dsn = "mysql:host=$dbHost;dbname=$dbName";
$options = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
];
try {
$pdo = new PDO($dsn, $dbUsername, $dbPassword, $options);
// Fetch URLs from the database
$urls = [];
$query = $pdo->query('SELECT permalink FROM cmsb__permalinks WHERE old=0');
while ($row = $query->fetch(PDO::FETCH_ASSOC)) {
$urls[] = $row['permalink'];
}
// Check if URLs were found
if (empty($urls)) {
$error = 'No URLs found in the database.';
} else {
// Generate the sitemap XML content
$sitemapContent = generateSitemap($baseUrl, $urls);
// Store sitemap content in session for later use
$_SESSION['sitemap_content'] = $sitemapContent;
$success = "Sitemap generated successfully! Found " . count($urls) . " URLs. Choose what to do with your sitemap:";
$sitemapGenerated = true;
}
} catch (PDOException $e) {
$error = 'Database error: ' . $e->getMessage();
}
}
}
// Display the form and results
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Sitemap Generator</title>
<style>
body {
font-family: Arial, sans-serif;
max-width: 600px;
margin: 50px auto;
padding: 20px;
background-color: #f5f5f5;
}
.container {
background-color: white;
padding: 30px;
border-radius: 8px;
box-shadow: 0 2px 10px rgba(0,0,0,0.1);
}
h1 {
color: #333;
text-align: center;
margin-bottom: 30px;
}
.form-group {
margin-bottom: 20px;
}
label {
display: block;
margin-bottom: 5px;
font-weight: bold;
color: #555;
}
input[type="text"], input[type="password"] {
width: 100%;
padding: 10px;
border: 1px solid #ddd;
border-radius: 4px;
font-size: 16px;
box-sizing: border-box;
}
input[type="text"]:focus, input[type="password"]:focus {
border-color: #4CAF50;
outline: none;
}
.submit-btn {
background-color: #4CAF50;
color: white;
padding: 12px 30px;
border: none;
border-radius: 4px;
cursor: pointer;
font-size: 16px;
width: 100%;
}
.submit-btn:hover {
background-color: #45a049;
}
.action-btn {
display: inline-block;
padding: 8px 16px;
margin-right: 10px;
margin-bottom: 5px;
text-decoration: none;
border-radius: 4px;
font-size: 14px;
font-weight: bold;
transition: background-color 0.3s;
}
.replace-btn {
background-color: #4CAF50;
color: white;
}
.replace-btn:hover {
background-color: #45a049;
}
.download-btn {
background-color: #2196F3;
color: white;
}
.download-btn:hover {
background-color: #1976D2;
}
.view-btn {
background-color: #FF9800;
color: white;
}
.view-btn:hover {
background-color: #F57C00;
}
.error {
background-color: #ffebee;
color: #c62828;
padding: 10px;
border-radius: 4px;
margin-bottom: 20px;
}
.success {
background-color: #e8f5e8;
color: #2e7d32;
padding: 10px;
border-radius: 4px;
margin-bottom: 20px;
}
.note {
background-color: #fff3cd;
color: #856404;
padding: 10px;
border-radius: 4px;
margin-bottom: 20px;
font-size: 14px;
}
</style>
</head>
<body>
<div class="container">
<h1>Sitemap Generator</h1>
<?php if (isset($error)): ?>
<div class="error"><?php echo htmlspecialchars($error); ?></div>
<?php endif; ?>
<?php if (isset($replace_success)): ?>
<div class="success"><?php echo htmlspecialchars($replace_success); ?></div>
<?php endif; ?>
<?php if (isset($success) && isset($sitemapGenerated)): ?>
<div class="success">
<?php echo htmlspecialchars($success); ?>
<div style="margin-top: 15px;">
<a href="?action=replace" class="action-btn replace-btn">🔄 Replace sitemap.xml in root</a>
<a href="?action=download" class="action-btn download-btn">📥 Download sitemap.xml</a>
<a href="?action=view" class="action-btn view-btn" target="_blank">👁️ View in Browser</a>
</div>
</div>
<?php elseif (isset($success)): ?>
<div class="success"><?php echo htmlspecialchars($success); ?></div>
<?php endif; ?>
<div class="note">
<strong>Note:</strong> This script will generate a sitemap.xml using permalinks from the cmsb__permalinks table where old=0. After generation, you can choose to replace the existing sitemap.xml in your root directory, download it to your computer, or view it in your browser.
</div>
<form method="POST" action="">
<div class="form-group">
<label for="base_url">Website Base URL *</label>
<input type="text" id="base_url" name="base_url"
value="<?php echo isset($_POST['base_url']) ? htmlspecialchars($_POST['base_url']) : 'https://www.yourwebsite.com'; ?>"
placeholder="https://www.yourwebsite.com" required>
</div>
<div class="form-group">
<label for="db_host">Database Host *</label>
<input type="text" id="db_host" name="db_host"
value="<?php echo isset($_POST['db_host']) ? htmlspecialchars($_POST['db_host']) : 'localhost'; ?>"
placeholder="localhost" required>
</div>
<div class="form-group">
<label for="db_name">Database Name *</label>
<input type="text" id="db_name" name="db_name"
value="<?php echo isset($_POST['db_name']) ? htmlspecialchars($_POST['db_name']) : ''; ?>"
placeholder="yourdatabase" required>
</div>
<div class="form-group">
<label for="db_username">Database Username *</label>
<input type="text" id="db_username" name="db_username"
value="<?php echo isset($_POST['db_username']) ? htmlspecialchars($_POST['db_username']) : ''; ?>"
placeholder="yourusername" required>
</div>
<div class="form-group">
<label for="db_password">Database Password</label>
<input type="password" id="db_password" name="db_password"
value="<?php echo isset($_POST['db_password']) ? htmlspecialchars($_POST['db_password']) : ''; ?>"
placeholder="yourpassword">
</div>
<button type="submit" name="generate_sitemap" class="submit-btn">
Generate Sitemap
</button>
</form>
</div>
</body>
</html>
<?php
} else {
echo "This script can only be run from a web browser.";
}
?>