Smarty 實現定期創建網站sitemap

實現思路:

1. 創建xml模板文件。
     <?xml version="1.0" encoding="UTF-8"?>
<urlset>
    <url>
        <loc>http://www.mimujiang.com/</loc>
        <lastmod><{$date}></lastmod>
        <changefreq>daily</changefreq>
        <priority>1.0</priority>
    </url>
    <url>
        <loc>http://www.mimujiang.com/service.shtml</loc>
        <lastmod><{$date}></lastmod>
        <changefreq>daily</changefreq>
        <priority>1.0</priority>
    </url>
    <url>
        <loc>http://www.mimujiang.com/product.shtml?areaid=0</loc>
        <lastmod><{$date}></lastmod>
        <changefreq>daily</changefreq>
        <priority>1.0</priority>
    </url>
    <url>
        <loc>http://www.mimujiang.com/aboutus.shtml</loc>
        <lastmod><{$date}></lastmod>
        <changefreq>daily</changefreq>
        <priority>1.0</priority>
    </url>
    <url>
        <loc>http://www.mimujiang.com/signup.shtml</loc>
        <lastmod><{$date}></lastmod>
        <changefreq>daily</changefreq>
        <priority>1.0</priority>
    </url>
     <{foreach from = $product_id item = i}>
    <url>
        <loc>http://www.mimujiang.com/service/product/detail/<{$i.product_id}></loc>
        <lastmod><{$date}></lastmod>
        <changefreq>daily</changefreq>
        <priority>1.0</priority>
    </url>
     <{/foreach}>

</urlset>
紅色部分表示:需要動態變化的部分。在控制器中給對應變化部分進行賦值。
2. 模型部分的實現:
xml文件中需要變化的部分是產品的id,需要通過數據庫查詢出結果。
function get_all_productid($table = 'm_products'){
          $sql = 'SELECT product_id from ' . $table . ' WHERE is_on_sale = 1 AND is_delete = 0';
          $query = $this->db->query($sql);
          $result = $query->result_array();
          return $result;
     }
3. 控制器部分的實現:
     function mksitemap(){
          //get product_id from table m_products
          $product_id = $this->mym->get_all_productid();
          $this->smarty->assign('date',date('Y-m-d'));
          $this->smarty->assign('product_id',$product_id);
          $contents = $this->smarty->fetch('sitemap.tpl');
          //print string to xml format
          $file = '../sitemap.xml';
          file_put_contents($file, $contents);
     }
     /*
     首先獲取數據,包括:產品id和當前日期,
     其次:把獲取的數據賦給模板變量。
     最後,獲取模板的內容。
          注:此處使用的smarty自帶的fetch函數實現的。直接獲取xml模板文件的所有內容。
     使用PHP的file_put_contents()函數,把數據寫進網站根目錄中sitemap.xml文件。
4. 定期更新:
     定期更新的問題(即每天執行一次),需要在服務器上執行指令,即可實現該方法的定期執行。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章