【问题标题】:Multiple sitemaps with php使用 php 的多个站点地图
【发布时间】:2013-05-20 21:42:31
【问题描述】:

我有一个网站,我会定期向其中添加页面日志。目前我正在遍历我的数据库以获取几百个 URL,然后将它们添加到 sitemap-1,然后获取接下来的几百个并将它们添加到 sitemap-2。这一切都是我手工完成的。

我想使用一个 while 循环来创建所有新页面并将它们插入到数据库中。它应该检查我当前的站点地图-x 以确定是否达到 URL 计数阈值,然后创建一个新的站点地图++并开始添加页面或只是添加到当前站点地图。

我怎样才能做到这一点?

我有一些代码来创建站点地图,但我不确定如何检查它是否已满 2000 个 url,然后继续创建一个新的。

<?php


/* create a dom document with encoding utf8 */
$domtree = new DOMDocument('1.0', 'UTF-8');

/* create the root element of the xml tree */
$xmlRoot = $domtree->createElement("urlset");
$xmlRoot -> appendChild(new DomAttr('xmlns',  'http://www.sitemaps.org/schemas/sitemap/0.9'));
$xmlRoot -> appendChild(new DomAttr('xmlns:xsi', 'http://www.w3.org/2001/XMLSchema-instance'));
$xmlRoot -> appendChild(new DomAttr('xsi:schemaLocation', 'http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd'));

/* append it to the document created */
$xmlRoot = $domtree->appendChild($xmlRoot);

/* tehloop */
while ($row = mysql_fetch_array($result)){
    $currentTrack = $domtree->createElement("url");
    $currentTrack = $xmlRoot->appendChild($currentTrack);
    $currentTrack->appendChild($domtree->createElement('loc','website'));
    $currentTrack->appendChild($domtree->createElement('changefreq','weekly'));
    $currentTrack->appendChild($domtree->createElement('priority','1.0'));
}

/* save the xml sitemap */
$domtree->formatOutput = true;
$domtree->preserveWhitespace = false;
$domtree->save('sitemap.xml'); 

?>

【问题讨论】:

  • 站点地图是做什么用的?

标签: php xml sitemap


【解决方案1】:
$tracks = array();
$count = 0;

while ($row = mysql_fetch_array($result)){
    if($count >= 2000){
        $count = 0;
        array_push($currentTrack);
        unset($currentTrack);
        //Reset your domtree object here too...
    }
    $currentTrack = $domtree->createElement("url");
    $currentTrack = $xmlRoot->appendChild($currentTrack);
    $currentTrack->appendChild($domtree->createElement('loc','website'));
    $currentTrack->appendChild($domtree->createElement('changefreq','weekly'));
    $currentTrack->appendChild($domtree->createElement('priority','1.0'));
}

//Now for each array index loop through file creation 
for($i = 0; $i < $tracks.length; $i++){
    /* save the xml sitemap */
    $domtree->formatOutput = true;
    $domtree->preserveWhitespace = false;
    $domtree->save('sitemap' . $i . '.xml'); 
}

您必须在此处添加代码以重置您的 domtree 并进行适当的修复以使其正常工作,但您明白了。

【讨论】:

  • 通过再次复制 domroot 和 xmlroot 变量来重置 domtree 对象?
  • 好吧,既然你在这里吐出文件,我会说做与 $currentTrack 变量相同的事情。取消设置它们,然后重新初始化它们。当您需要能够为每个 DOM 设置不同的属性时,这将有利于未来。此外,将 DOM 树的创建封装在一个函数中,您将拥有更少的维护麻烦和更简洁的代码。
猜你喜欢
  • 2011-06-30
  • 1970-01-01
  • 1970-01-01
  • 2011-09-19
  • 2016-11-05
  • 1970-01-01
  • 2017-02-04
  • 2014-06-02
  • 2011-02-14
相关资源
最近更新 更多