使用PHP创建多个站点地图

5
我有以下问题,我生成了网站地图的URL,并将它们存储在一个数组中。因此,这个数组有60000个条目。而Google要求我创建2个网站地图,因为每个网站地图的限制是50000个条目。
请问如何通过PHP实现呢?我已经尝试过,但在循环停止并将其他数据输入到另一个文件时遇到了问题。以下是我的代码:
// $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);


}

我需要一个动态解决方案,谢谢帮助。
2个回答

4

array_chunk函数是您的好帮手:

$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);
}

可以直接使用,适用于不同数量的站点地图。


@AlixAxel:https://dev59.com/questions/8Jjga4cB1Zd3GeqPMpuR - NewCod3r
我如何在不加载所有数据到数组中的情况下使用它?我有500万条记录,将所有记录加载到数组中可能会耗尽我的内存。 - user1642018

0
$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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接