php 实现sitemap
PHP 实现 Sitemap 的方法
使用 PHP 生成静态 XML Sitemap
创建一个 PHP 脚本,生成符合搜索引擎标准的 XML Sitemap 文件。以下是一个基础实现示例:
<?php
header('Content-type: application/xml; charset=utf-8');
echo '<?xml version="1.0" encoding="UTF-8"?>';
echo '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">';
// 示例数据 - 实际应从数据库或动态获取
$urls = [
['loc' => 'https://example.com/', 'lastmod' => '2023-01-01', 'changefreq' => 'daily', 'priority' => '1.0'],
['loc' => 'https://example.com/about', 'lastmod' => '2023-01-02', 'changefreq' => 'monthly', 'priority' => '0.8']
];
foreach ($urls as $url) {
echo '<url>';
echo '<loc>' . htmlspecialchars($url['loc']) . '</loc>';
echo '<lastmod>' . $url['lastmod'] . '</lastmod>';
echo '<changefreq>' . $url['changefreq'] . '</changefreq>';
echo '<priority>' . $url['priority'] . '</priority>';
echo '</url>';
}
echo '</urlset>';
?>
动态生成 Sitemap 内容
对于动态网站,可以从数据库获取所有公开页面的 URL:

// 假设使用 PDO 连接数据库
$stmt = $pdo->query("SELECT url, last_updated FROM pages WHERE published = 1");
while ($row = $stmt->fetch()) {
echo '<url>';
echo '<loc>' . htmlspecialchars($row['url']) . '</loc>';
echo '<lastmod>' . date('Y-m-d', strtotime($row['last_updated'])) . '</lastmod>';
echo '</url>';
}
分块处理大型 Sitemap
当 URL 数量超过 50,000 时,需要创建 Sitemap 索引文件:
// sitemap_index.php
echo '<?xml version="1.0" encoding="UTF-8"?>';
echo '<sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">';
echo '<sitemap><loc>https://example.com/sitemap1.xml</loc></sitemap>';
echo '<sitemap><loc>https://example.com/sitemap2.xml</loc></sitemap>';
echo '</sitemapindex>';
自动更新机制
设置定时任务(Cron Job)定期重新生成 Sitemap:

# 每天凌晨更新
0 0 * * * php /path/to/generate_sitemap.php
通知搜索引擎
生成后通过搜索引擎的提交接口(如 Google Search Console API)自动提交:
$sitemapUrl = 'https://example.com/sitemap.xml';
$apiUrl = 'https://www.google.com/webmasters/sitemaps/ping?sitemap=' . urlencode($sitemapUrl);
file_get_contents($apiUrl);
使用第三方库
对于复杂需求,可以使用专用库如 Laravelium/laravel-sitemap(Laravel 项目):
// Laravel 示例
SitemapGenerator::create('https://example.com')
->getSitemap()
->add(Url::create('/about'))
->writeToFile(public_path('sitemap.xml'));
最佳实践
- 确保只包含可索引的公开 URL
- 优先使用 HTTPS URL
- 合理设置 changefreq 和 priority
- 对大型网站使用 gzip 压缩 sitemap 文件
- 在 robots.txt 中声明 sitemap 位置
以上方法可根据实际项目需求组合使用,实现高效的 sitemap 生成和管理。






