本文目录导读:

我来介绍几种PHP生成sitemap的方法:
基础XML格式的Sitemap
<?php
// 简单XML方式生成sitemap
function generateBasicSitemap($urls) {
$xml = new DOMDocument('1.0', 'UTF-8');
$xml->formatOutput = true;
// 创建根节点
$urlset = $xml->createElement('urlset');
$urlset->setAttribute('xmlns', 'http://www.sitemap.org/schemas/sitemap/0.9');
$xml->appendChild($urlset);
// 添加每个URL
foreach ($urls as $url) {
$urlElement = $xml->createElement('url');
// URL地址
$loc = $xml->createElement('loc', $url['loc']);
$urlElement->appendChild($loc);
// 最后修改时间
$lastmod = $xml->createElement('lastmod', $url['lastmod'] ?? date('Y-m-d'));
$urlElement->appendChild($lastmod);
// 更新频率
$changefreq = $xml->createElement('changefreq', $url['changefreq'] ?? 'daily');
$urlElement->appendChild($changefreq);
// 优先级
$priority = $xml->createElement('priority', $url['priority'] ?? '0.5');
$urlElement->appendChild($priority);
$urlset->appendChild($urlElement);
}
return $xml->saveXML();
}
// 使用示例
$urls = [
[
'loc' => 'https://example.com/',
'lastmod' => '2024-01-01',
'changefreq' => 'daily',
'priority' => '1.0'
],
[
'loc' => 'https://example.com/about',
'lastmod' => '2024-01-15',
'changefreq' => 'monthly',
'priority' => '0.8'
]
];
$sitemap = generateBasicSitemap($urls);
file_put_contents('sitemap.xml', $sitemap);
使用数组和循环方式
<?php
function generateSitemapFromArray($data) {
$xml = '<?xml version="1.0" encoding="UTF-8"?>' . "\n";
$xml .= '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">' . "\n";
foreach ($data as $item) {
$xml .= " <url>\n";
$xml .= " <loc>" . htmlspecialchars($item['loc']) . "</loc>\n";
if (!empty($item['lastmod'])) {
$xml .= " <lastmod>" . $item['lastmod'] . "</lastmod>\n";
}
if (!empty($item['changefreq'])) {
$xml .= " <changefreq>" . $item['changefreq'] . "</changefreq>\n";
}
if (!empty($item['priority'])) {
$xml .= " <priority>" . $item['priority'] . "</priority>\n";
}
$xml .= " </url>\n";
}
$xml .= '</urlset>';
return $xml;
}
从数据库生成Sitemap
<?php
class SitemapGenerator {
private $db;
public function __construct($dbConnection) {
$this->db = $dbConnection;
}
public function generateFromDatabase() {
$urls = [];
// 从文章表获取数据
$query = "SELECT slug, updated_at FROM articles WHERE status = 'published'";
$result = $this->db->query($query);
while ($row = $result->fetch_assoc()) {
$urls[] = [
'loc' => 'https://example.com/article/' . $row['slug'],
'lastmod' => date('Y-m-d', strtotime($row['updated_at'])),
'changefreq' => 'monthly',
'priority' => '0.7'
];
}
// 从分类表获取数据
$query = "SELECT slug, name FROM categories";
$result = $this->db->query($query);
while ($row = $result->fetch_assoc()) {
$urls[] = [
'loc' => 'https://example.com/category/' . $row['slug'],
'lastmod' => date('Y-m-d'),
'changefreq' => 'weekly',
'priority' => '0.6'
];
}
return generateBasicSitemap($urls);
}
}
使用第三方库(推荐)
<?php
// 使用 composer 安装: composer require samdark/sitemap
require 'vendor/autoload.php';
use samdark\sitemap\Sitemap;
use samdark\sitemap\Index;
// 创建单个 sitemap
$sitemap = new Sitemap(__DIR__ . '/sitemap.xml');
$sitemap->addItem('https://example.com/', time(), Sitemap::DAILY, '1.0');
$sitemap->addItem('https://example.com/about', time(), Sitemap::MONTHLY, '0.8');
// 更多项目...
$sitemap->write();
// 创建 sitemap index(适用于大批量URL)
$index = new Index(__DIR__ . '/sitemap_index.xml');
$index->addSitemap('https://example.com/sitemap1.xml');
$index->addSitemap('https://example.com/sitemap2.xml');
$index->write();
完整的HTML表单示例
<?php
// sitemap_generator.php
class AdvancedSitemapGenerator {
public function generate() {
$urls = $this->getAllUrls();
$sitemap = $this->createSitemap($urls);
// 保存到文件
$this->saveToFile($sitemap, 'sitemap.xml');
// 可选:提交到搜索引擎
$this->notifySearchEngines();
return $sitemap;
}
private function getAllUrls() {
$urls = [];
// 静态页面
$staticPages = [
['/', 'daily', '1.0'],
['/about', 'monthly', '0.8'],
['/contact', 'monthly', '0.7'],
['/privacy', 'yearly', '0.3']
];
foreach ($staticPages as $page) {
$urls[] = [
'loc' => 'https://example.com' . $page[0],
'lastmod' => date('Y-m-d'),
'changefreq' => $page[1],
'priority' => $page[2]
];
}
// 动态内容(示例)
// $urls = array_merge($urls, $this->getArticles());
// $urls = array_merge($urls, $this->getProducts());
return $urls;
}
private function createSitemap($urls) {
// 使用DOMDocument创建
$dom = new DOMDocument('1.0', 'UTF-8');
$dom->formatOutput = true;
$root = $dom->createElement('urlset');
$root->setAttribute('xmlns', 'http://www.sitemaps.org/schemas/sitemap/0.9');
$dom->appendChild($root);
foreach ($urls as $url) {
$urlNode = $dom->createElement('url');
$loc = $dom->createElement('loc', $url['loc']);
$urlNode->appendChild($loc);
if (isset($url['lastmod'])) {
$lastmod = $dom->createElement('lastmod', $url['lastmod']);
$urlNode->appendChild($lastmod);
}
// 其他字段...
$root->appendChild($urlNode);
}
return $dom->saveXML();
}
private function saveToFile($content, $filename) {
file_put_contents($filename, $content);
}
private function notifySearchEngines() {
$sitemapUrl = 'https://example.com/sitemap.xml';
// 通知Google
$googleUrl = "http://www.google.com/ping?sitemap=" . urlencode($sitemapUrl);
@file_get_contents($googleUrl);
// 通知Bing
$bingUrl = "http://www.bing.com/ping?sitemap=" . urlencode($sitemapUrl);
@file_get_contents($bingUrl);
}
}
最佳实践建议
<?php
// 自动生成sitemap的最佳实践
function autoGenerateSitemap() {
// 1. 检查是否有更新
$lastGenerated = filemtime('sitemap.xml');
$timeSinceLast = time() - $lastGenerated;
// 2. 如果超过24小时或有新内容,重新生成
if ($timeSinceLast > 86400 || hasNewContent()) {
$generator = new SitemapGenerator($db);
$sitemap = $generator->generateFromDatabase();
file_put_contents('sitemap.xml', $sitemap);
// 3. 记录生成时间
updateSitemapLog();
}
}
// 4. 在 robots.txt 中添加
/*
User-agent: *
Allow: /
Sitemap: https://example.com/sitemap.xml
*/
使用注意事项:
- Sitemap 大小限制:单个 sitemap 最多 50MB 或 50,000 个 URL
- 压缩格式:可以使用 .xml.gz 压缩格式
- 更新频率更新频繁度设置合理的 changefreq
- 优先级:priority 值范围 0.0-1.0
- 编码:确保使用 UTF-8 编码
- URL格式:使用绝对URL,并转义特殊字符
选择哪种方法取决于你的项目复杂度,建议使用成熟的第三方库来处理大型sitemap的生成。