PHP生成sitemap怎么弄

wen PHP项目 5

本文目录导读:

PHP生成sitemap怎么弄

  1. 基础XML Sitemap生成
  2. 创建sitemap索引文件
  3. 自动生成并保存为文件
  4. 使用cron自动更新
  5. 使用第三方库
  6. 提交到搜索引擎
  7. 建议

在PHP中生成sitemap(站点地图)有多种方法,我来为你详细介绍几种常见方案:

基础XML Sitemap生成

简单静态Sitemap

<?php
// 创建sitemap内容
$urls = [
    ['loc' => 'https://example.com/', 'priority' => '1.0', 'changefreq' => 'daily'],
    ['loc' => 'https://example.com/about', 'priority' => '0.8', 'changefreq' => 'monthly'],
    ['loc' => 'https://example.com/contact', 'priority' => '0.7', 'changefreq' => 'monthly'],
];
// 生成XML
header('Content-Type: application/xml; charset=utf-8');
echo '<?xml version="1.0" encoding="UTF-8"?>' . "\n";
echo '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">' . "\n";
foreach ($urls as $url) {
    echo "  <url>\n";
    echo "    <loc>{$url['loc']}</loc>\n";
    echo "    <priority>{$url['priority']}</priority>\n";
    echo "    <changefreq>{$url['changefreq']}</changefreq>\n";
    echo "  </url>\n";
}
echo '</urlset>';
?>

动态从数据库生成

<?php
// 连接数据库获取URL列表
function getSiteUrls($pdo) {
    $urls = [];
    // 获取文章页面
    $stmt = $pdo->query("SELECT slug, updated_at FROM articles WHERE status = 'published'");
    while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
        $urls[] = [
            'loc' => 'https://example.com/article/' . $row['slug'],
            'lastmod' => $row['updated_at'],
            'priority' => '0.8',
            'changefreq' => 'weekly'
        ];
    }
    // 获取分类页面
    $stmt = $pdo->query("SELECT slug FROM categories");
    while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
        $urls[] = [
            'loc' => 'https://example.com/category/' . $row['slug'],
            'priority' => '0.6',
            'changefreq' => 'monthly'
        ];
    }
    return $urls;
}
// 生成sitemap
function generateSitemap($pdo) {
    $urls = getSiteUrls($pdo);
    header('Content-Type: application/xml; charset=utf-8');
    $xml = new SimpleXMLElement(
        '<?xml version="1.0" encoding="UTF-8"?>' .
        '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">'
    );
    foreach ($urls as $url) {
        $node = $xml->addChild('url');
        $node->addChild('loc', $url['loc']);
        if (isset($url['lastmod'])) {
            $node->addChild('lastmod', date('Y-m-d', strtotime($url['lastmod'])));
        }
        $node->addChild('priority', $url['priority']);
        $node->addChild('changefreq', $url['changefreq']);
    }
    return $xml->asXML();
}
// 使用
$pdo = new PDO('mysql:host=localhost;dbname=your_db', 'username', 'password');
echo generateSitemap($pdo);
?>

创建sitemap索引文件

当网站很大时,需要分割成多个sitemap:

<?php
// sitemap_index.php
header('Content-Type: application/xml; charset=utf-8');
echo '<?xml version="1.0" encoding="UTF-8"?>' . "\n";
echo '<sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">' . "\n";
// 分页生成
for ($i = 1; $i <= 5; $i++) {
    echo "  <sitemap>\n";
    echo "    <loc>https://example.com/sitemap-{$i}.php</loc>\n";
    echo "    <lastmod>" . date('Y-m-d') . "</lastmod>\n";
    echo "  </sitemap>\n";
}
echo '</sitemapindex>';
?>

自动生成并保存为文件

<?php
// 生成并保存sitemap文件
function createSitemapFile($data) {
    $sitemap = new SimpleXMLElement(
        '<?xml version="1.0" encoding="UTF-8"?>' .
        '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">'
    );
    foreach ($data as $url) {
        $node = $sitemap->addChild('url');
        $node->addChild('loc', $url['loc']);
        $node->addChild('lastmod', date('c', strtotime($url['lastmod'] ?? 'now')));
        $node->addChild('changefreq', $url['changefreq'] ?? 'daily');
        $node->addChild('priority', $url['priority'] ?? '0.5');
    }
    // 格式化输出
    $dom = new DOMDocument('1.0');
    $dom->preserveWhiteSpace = false;
    $dom->formatOutput = true;
    $dom->loadXML($sitemap->asXML());
    // 保存到文件
    $dom->save($_SERVER['DOCUMENT_ROOT'] . '/sitemap.xml');
    return true;
}
// 调用示例
$urls = [
    ['loc' => 'https://example.com/', 'priority' => '1.0'],
    ['loc' => 'https://example.com/products', 'priority' => '0.9'],
];
createSitemapFile($urls);
echo "Sitemap已生成!";
?>

使用cron自动更新

<?php
// auto_sitemap.php - 计划任务脚本
error_reporting(E_ALL);
ini_set('display_errors', 1);
class SitemapGenerator {
    private $pdo;
    private $baseUrl;
    public function __construct(PDO $pdo, string $baseUrl) {
        $this->pdo = $pdo;
        $this->baseUrl = rtrim($baseUrl, '/');
    }
    public function generate() {
        $sitemap = new SimpleXMLElement(
            '<?xml version="1.0" encoding="UTF-8"?>' .
            '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">'
        );
        // 添加主页
        $this->addUrl($sitemap, ['loc' => $this->baseUrl, 'priority' => '1.0']);
        // 添加产品页面
        $stmt = $this->pdo->query("SELECT * FROM products WHERE status = 1");
        while ($product = $stmt->fetch()) {
            $this->addUrl($sitemap, [
                'loc' => "$this->baseUrl/product/",
                'lastmod' => $product['updated_at'],
                'changefreq' => 'weekly',
                'priority' => '0.8'
            ]);
        }
        return $sitemap->asXML();
    }
    private function addUrl($sitemap, $data) {
        $url = $sitemap->addChild('url');
        foreach ($data as $tag => $value) {
            $url->addChild($tag, htmlspecialchars($value));
        }
    }
}
// 使用
try {
    $pdo = new PDO('mysql:host=localhost;dbname=your_db', 'user', 'pass');
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $generator = new SitemapGenerator($pdo, 'https://example.com');
    $sitemap = $generator->generate();
    // 保存到文件
    file_put_contents(__DIR__ . '/sitemap.xml', $sitemap);
    echo "Sitemap更新成功!";
} catch (Exception $e) {
    echo "错误: " . $e->getMessage();
}
?>

使用第三方库

如果使用Composer,推荐使用这些库:

composer require samdark/sitemap
<?php
use samdark\sitemap\Sitemap;
use samdark\sitemap\Index;
// 创建sitemap
$sitemap = new Sitemap(__DIR__ . '/sitemap.xml');
$sitemap->addItem('https://example.com/', '1.0', 'daily', time());
$sitemap->addItem('https://example.com/page1', '0.9', 'weekly', time());
$sitemap->write();
// 或创建索引
$index = new Index(__DIR__ . '/sitemap.xml');
$index->addSitemap('https://example.com/sitemap-1.xml');
$index->write();
?>

提交到搜索引擎

<?php
// 提交到Google
function submitToGoogle($sitemapUrl) {
    $url = 'http://www.google.com/ping?sitemap=' . urlencode($sitemapUrl);
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $response = curl_exec($ch);
    curl_close($ch);
    return $response;
}
// 提交到Bing
function submitToBing($sitemapUrl) {
    $url = 'https://www.bing.com/ping?sitemap=' . urlencode($sitemapUrl);
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $response = curl_exec($ch);
    curl_close($ch);
    return $response;
}
// 调用
$sitemapUrl = 'https://example.com/sitemap.xml';
submitToGoogle($sitemapUrl);
submitToBing($sitemapUrl);
?>

建议

  1. 自动更新:使用cron定期生成sitemap
  2. 压缩优化:可以生成gzip压缩版本的sitemap.xml.gz
  3. 限制大小:每个sitemap最多50,000个URL和50MB
  4. 错误处理:确保URL都是有效的
  5. 缓存:定期生成并缓存,避免频繁生成

定时任务配置示例:

# crontab -e
0 2 * * * php /path/to/auto_sitemap.php

这样就能自动化保持sitemap更新了!

抱歉,评论功能暂时关闭!