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. 定期更新:
     定期更新的问题(即每天执行一次),需要在服务器上执行指令,即可实现该方法的定期执行。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值