开发者

Creating multiple Sitemaps in PHP

开发者 https://www.devze.com 2023-02-12 10:54 出处:网络
i have following problem, i generated the urls for th开发者_StackOverflow中文版e sitemap, in a array. So the array has 60000 entries. And google wants me to create 2 sitemaps cause the limit is 50000

i have following problem, i generated the urls for th开发者_StackOverflow中文版e sitemap, in a array. So the array has 60000 entries. And google wants me to create 2 sitemaps cause the limit is 50000 entries each sitemap.

How can i make this with php? I tried it, but have problems with the loop to stop and enter the other data in the other file. Here is my code sofar.

// $data is array with the urls
$count_array = count($data);
$maxlinksinsitemap = 50000;
$numbersofsitemap = ceil($count_array / $maxlinksinsitemap);

for($i = 1; $i <= $numbersofsitemap; $i++) {
    $cfile = "sitemap_" .$i . ".xml";
    $createfile = fopen($cfile, 'w');
    $creat = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
    $creat .= "<urlset xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\"\n";
    $creat .= "xmlns:image=\"http://www.sitemaps.org/schemas/sitemap-image/1.1\"\n";
    $creat .= "xmlns:video=\"http://www.sitemaps.org/schemas/sitemap-video/1.1\">\n";
    $creat .= "<url>\n";
    $creat .= "<loc>http://www.urltosite.com</loc>\n";
    $creat .= "<priority>1.00</priority>\n";
    $creat .= "</url>\n";


    $creat .= "</urlset>";  
    fwrite($createfile, $creat);    
    fclose($createfile);


}

I need a dynamic solution,

Thanks for help.


array_chunk is your friend:

$data = array_chunk($data, 50000);

foreach ($data as $key => $value)
{
    $cfile = 'sitemap_' . $i  . '.xml';
    $createfile = fopen($cfile, 'w');

    fwrite($createfile, "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
    fwrite($createfile, "<urlset xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\"\n");
    fwrite($createfile, "xmlns:image=\"http://www.sitemaps.org/schemas/sitemap-image/1.1\"\n");
    fwrite($createfile, "xmlns:video=\"http://www.sitemaps.org/schemas/sitemap-video/1.1\">\n");

    foreach ($value as $url)
    {
        $creat = "<url>\n";
        $creat .= "<loc>" . $url . "</loc>\n";
        $creat .= "<priority>1.00</priority>\n";
        $creat .= "</url>\n";

        fwrite($createfile, $creat);
    }

    fclose($createfile);
}

Works with a variable number of sitemaps out of the box.


$count_array = count($data);
$i = 0;

foreach ($data as $entry) {
    if ($i == 0) {
        // code here to start first file
    } else if ($i % 50000 == 0) {
        // code here to end previous file and start next file
    }

    // write entry to current file
    // insert code here....

    // increment counter
    $i++;
}

// code here to end last file
0

精彩评论

暂无评论...
验证码 换一张
取 消