生成多sitemap文件


Thinkphp生成多sitemap文件  

我們知道sitemap對於seo的重要性,很多介紹只生成一個文件sitemap.xml ,但是如果網站內容比較多,就要生成多個sitemap文件,因為搜索引擎對sitemap文件大小和條數有限制,比如google對每個sitemap文件的限制為5萬條數據。

何為多sitemap文件機制? 首先我們生成一個主sitemap文件,此文件為sitemapindex類型,其中存放子sitemap文件的路徑。子sitemap文件用來存放具體文章item. 這里我們假定每個子sitemap存放網址數為10000個。則代碼如下(這里用的thinkphp框架,原理都是一樣的):

 

class SitemapAction extends Action { 
     
   //生成sitemap 
    public function create() {
                $page_size    =    10000; //每頁條數
                $bp_db    =    M('BaobeiProducts');
                //1w個地址生成一個子地圖,判斷需要生成幾個?
                $count        =    $bp_db->where('status = 1')->count();
                $page_count    =    ceil($count/$page_size);  //分幾個文件
                
                $this->create_index($page_count);    //生成主sitemap
                $this->create_child($page_count,$page_size);    //生成子sitemap
                
 
            $this->success('地圖生成成功'); 
        
    }
    
    //生成主sitemap
    protected function create_index($page_count) {
    
                $content    =    "<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n<sitemapindex xmlns=\" http://www.sitemaps.org/schemas/sitemap/0.9\">\r\n";
                for($i=1;$i<=$page_count;$i++) {
                    
                        $content    .="<sitemap>\r\n<loc> http://HOST/sitemap/sitemap".$i.".xml</loc>\r\n<lastmod>".date('Y-m-d')."</lastmod>\r\n</sitemap>";
                }
                $content .= "</sitemapindex>";
                
                $file = fopen("sitemap.xml","w"); 
            fwrite($file,$content); 
            fclose($file);
    
    
   }
   
   //生成子sitemap
   protected function create_child($page_count,$page_size) {
       
       for($i=0;$i<$page_count;$i++) {

                   $list = M('BaobeiProducts')->field('id,m_time')->order('id asc')->limit($i*$page_size.','.$page_size)->select(); 
                
                $sitemap = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n<urlset xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\">\r\n"; 
                    foreach($list as $k=>$v){ 
                        $sitemap .= "<url>\r\n"."<loc>http://HOST/baobei/".$v['id']."</loc>\r\n"."<priority>0.6</priority>\r\n<lastmod>".date('Y-m-d',$v['m_time'])."</lastmod>\r\n<changefreq>weekly</changefreq>\r\n</url>\r\n"; 
             
                    } 
                 
                $sitemap .= '</urlset>'; 
                 
                $file = fopen("sitemap/sitemap".($i+1).".xml","w"); 
                fwrite($file,$sitemap); 
                fclose($file);
           }
       } 
 
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM