Büyük sitelerde sitemap index: 50.000 URL sınırını aşmak

Bir sitemap dosyası en fazla 50.000 URL ya da 50 MB (sıkıştırılmamış) olabiliyor. Bundan büyük sitelerde URL'leri birden fazla dosyaya bölüp hepsini bir sitemap index dosyasında toplaman gerekiyor.

Yapı

/sitemap.xml            ← index, sadece diğer sitemap'leri listeler
/sitemaps/urunler-1.xml
/sitemaps/urunler-2.xml
/sitemaps/yazilar-1.xml

Bölerek üretmek

sitemap-build.php
<?php
declare(strict_types=1);

const BASE = 'https://ornek.com';
const LIMIT = 45000; // sınırın biraz altında kalmak iyi fikir

$pdo = new PDO('mysql:host=localhost;dbname=site;charset=utf8mb4', 'kullanici', 'sifre');
$rows = $pdo->query("SELECT url, updated_at FROM urunler WHERE aktif = 1 ORDER BY id");

$files = [];
$part = 0;
$count = LIMIT;
$x = null;

foreach ($rows as $r) {
    if ($count >= LIMIT) {
        if ($x) { $x->endElement(); $x->flush(); }
        $part++;
        $file = "sitemaps/urunler-$part.xml";
        $files[] = $file;
        $x = new XMLWriter();
        $x->openUri(__DIR__ . "/$file");
        $x->startDocument('1.0', 'UTF-8');
        $x->startElement('urlset');
        $x->writeAttribute('xmlns', 'http://www.sitemaps.org/schemas/sitemap/0.9');
        $count = 0;
    }
    $x->startElement('url');
    $x->writeElement('loc', BASE . $r['url']);
    $x->writeElement('lastmod', date('c', strtotime($r['updated_at'])));
    $x->endElement();
    $count++;
}
if ($x) { $x->endElement(); $x->flush(); }

// index dosyası
$i = new XMLWriter();
$i->openUri(__DIR__ . '/sitemap.xml');
$i->startDocument('1.0', 'UTF-8');
$i->startElement('sitemapindex');
$i->writeAttribute('xmlns', 'http://www.sitemaps.org/schemas/sitemap/0.9');
foreach ($files as $f) {
    $i->startElement('sitemap');
    $i->writeElement('loc', BASE . '/' . $f);
    $i->writeElement('lastmod', date('c', filemtime(__DIR__ . "/$f")));
    $i->endElement();
}
$i->endElement();
$i->flush();
echo count($files) . " sitemap dosyası yazıldı\n";

openUri ile doğrudan dosyaya yazmak, milyonlarca satırda bile belleği şişirmiyor.

İpucu

Sitemap'leri türe göre böl (ürünler, kategoriler, yazılar). Search Console her sitemap için ayrı "dizine eklendi" sayısı gösteriyor. Hangi bölümde sorun olduğunu buradan görmek çok kolay.

Comments / questions

There's no comment section here. If you have a question or want to add something, message me on Telegram or send an email to [email protected]. Thanks!

Related pages