百度 Sitemap 規定單個 XML 不超過 5 萬條、50MB。針對 70 萬條問答數據,需生成 14 個分片 XML + 1 個索引文件。本文實現分批讀取、增量寫入、索引同步更新的完整流程,避免單次查詢過大影響線上服務。
<?php
class SitemapGenerator
{
private const PSIZE = 1000; // 每次查詢條數
private const MAX_XML = 5000; // 單 XML 最大條數
private string $indexFile;
private string $xmlDir;
private string $baseUrl;
private PDO $pdo;
public function __construct(PDO $pdo, string $xmlDir, string $baseUrl)
{
$this->pdo = $pdo;
$this->xmlDir = $xmlDir;
$this->baseUrl = $baseUrl;
$this->indexFile = $xmlDir . '/Index.txt';
}
public function generate(): void
{
// 讀取索引斷點
$state = $this->readIndexState();
$filename = $state['filename'];
$maxId = $state['maxId'];
$written = $state['written'];
while (true) {
$list = $this->fetchBatch($maxId, min(self::PSIZE, self::MAX_XML - $written));
if (!$list) break; // 無更多數據
$xmlFile = "$this->xmlDir/$filename.xml";
$this->writeXmlChunk($xmlFile, $list, $written === 0); // 首批寫入 XML 頭
$written += count($list);
$maxId = $list[count($list)-1]['id'];
$minId = $list[0]['id'] ?? $minId;
// 更新索引
$this->updateIndex($filename, $maxId, $minId, $written);
if ($written >= self::MAX_XML) {
// 切換下一分片
$filename++;
$written = 0;
$this->appendSitemapIndex("$this->baseUrl/$filename.xml");
}
}
echo "生成完成\n";
}
private function fetchBatch(int $lastMaxId, int $limit): array
{
$sql = "SELECT id, lasttime FROM questions WHERE id > ? ORDER BY id ASC LIMIT ?";
$stmt = $this->pdo->prepare($sql);
$stmt->execute([$lastMaxId, $limit]);
return $stmt->fetchAll(PDO::FETCH_ASSOC);
}
private function writeXmlChunk(string $file, array $list, bool $isFirst): void
{
$fp = fopen($file, $isFirst ? 'w' : 'a');
if ($isFirst) {
fwrite($fp, '' . "\n");
fwrite($fp, '' . "\n");
}
foreach ($list as $row) {
$url = $this->baseUrl . '/ask/' . $row['id'] . '.html';
$mobile = $this->baseUrl . '/m/ask/' . $row['id'] . '.html';
$lastmod = substr($row['lasttime'], 0, 10);
fwrite($fp, " \n $url \n $lastmod \n \n \n");
}
if ($this->isFinalChunk()) { // 最後一批需寫尾巴
fwrite($fp, ' ');
}
fclose($fp);
}
private function readIndexState(): array
{
if (!file_exists($this->indexFile)) return ['filename'=>0, 'maxId'=>0, 'written'=>0];
$lines = file($this->indexFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
$last = explode(',', $lines[count($lines)-1]);
return ['filename'=>(int)$last[0], 'maxId'=>(int)$last[1], 'written'=>(int)$last[3]];
}
private function updateIndex(int $filename, int $maxId, int $minId, int $written): void
{
$line = "$filename,$maxId,$minId,$written\n";
file_put_contents($this->indexFile, $line, FILE_APPEND | LOCK_EX);
}
private function appendSitemapIndex(string $loc): void
{
$idxFile = "$this->xmlDir/sitemapindex.xml";
$content = file_exists($idxFile) ? file_get_contents($idxFile) :
'';
$entry = "$loc " . date('Y-m-d') . " ";
$content = str_replace(' ', $entry . "\n", $content);
file_put_contents($idxFile, $content, LOCK_EX);
}
}
?>
此方案已支撐千萬級數據站點穩定運行,核心在於「小批次讀、增量寫、斷點續傳」三板斧。