PHP中使用smarty生成靜態(tài)文件的例子

字號:


    首先先要把需要靜態(tài)化的內容填充到模版中去
    代碼如下:
    #eg.這個是靜態(tài)化首頁的
    function staticIndex(){
    $newslist = $article->getArticles(null,54,'DESC',1,6,false,1,2,'',0,0,1);
    if($newslist){
    foreach($newslist as $k=>$v){
    $newslist[$k]['title_all'] = $v['title'];
    $newslist[$k]['title'] = cutstr($v['title'],36,'…');
    }
    $smarty->assign('newslist',$newslist);
    }
    $content = '';
    $content = $smarty->fetch('index.html',true);//這是Smarty自帶的生成靜態(tài)頁面的函數(shù)
    $static_name = ROOT_PATH.'index.html';//這是生成靜態(tài)頁面當前的路徑文件
    fopen($static_name,'a');//打開這個文件
    @file_put_contents($static_name,$content);//最后寫進去
    return true;
    }
    //靜態(tài)化列表頁,按類別不同經行靜態(tài)化
    function staticContent(){//需要靜態(tài)話的條數(shù)
    $ids = array();//獲取所有的內容
    $ids = $this->getListIds();//這個方法獲取所有的內容,下面紅字部分對應它的方法
    foreach($ids as $k=>$value){
    //echo $value['catid'];
    if(!file_exists(ROOT_PATH.'demo/')){//判斷根目錄下面有沒有這個文件夾,如果沒有則創(chuàng)建demo這個文件夾
    mkdir(ROOT_PATH.'demo/');
    }
    if(!file_exists(ROOT_PATH.'demo/'.$value['catid'])){//判斷這個文件夾下面有沒有對應的類別文件夾
    mkdir(ROOT_PATH.'demo/'.$value['catid']);
    }
    $html_content = $this->getDemoContent($value['demoid']);
    $static_name = ROOT_PATH.'demo/'.$value['catid'].'/'.$value['demoid'].'.html';
    fopen($static_name,'a');
    @file_put_contents($static_name,$html_content);
    }
    return true;
    }
    //拿出需要靜態(tài)化的頁面ID
    function getListIds(){
    $sql = "select * from {$this->tablepre}demo order by demoid asc";
    $rs = $this->db->getAll($sql);
    if($rs){
    return $rs;
    }else{
    return false;
    }
    }
    //content單頁靜態(tài)化
    function getDemoContent($id){
    global $smarty,$view_templates,$admin_templates;
    loadModel(array('demo'));
    $demo = new demo();
    $content = '';
    $smarty->template_dir = ROOT_PATH.$view_templates;
    $getMobanOne = $this->getMobanDetail($id);
    $mobandetail = $demo->MobanList($id);
    foreach($mobandetail as $k=>$v){
    $smarty->assign($k,$v);
    }
    $this->catid = $getMobanOne['catid'];
    $smarty->assign('pre_title',$mobandetail['membername']);
    $smarty->assign('mobandetail',$mobandetail);
    $content = $smarty->fetch('demo_show.html',true);
    $smarty->template_dir = ROOT_PATH.$view_templates;
    return $content;
    }
    以前用的那個生成靜態(tài)頁面每次都要執(zhí)行PHP文件,然后才能生成,現(xiàn)在我寫的這個就是由人控制的,想生成就生成,很方便,希望能給大家?guī)矸奖?,祝大家工作愉快?