Home >Backend Development >PHP Tutorial >PHP中使用smarty生成静态文件的例子_PHP

PHP中使用smarty生成静态文件的例子_PHP

WBOY
WBOYOriginal
2016-06-01 11:54:56981browse

首先先要把需要静态化的内容填充到模版中去


复制代码 代码如下:
#eg.这个是静态化首页的

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自带的生成静态页面的函数
$static_name = ROOT_PATH.'index.html';//这是生成静态页面当前的路径文件
fopen($static_name,'a');//打开这个文件
@file_put_contents($static_name,$content);//最后写进去
return true;
}

//静态化列表页,按类别不同经行静态化

function staticContent(){//需要静态话的条数
  $ids = array();//获取所有的内容
   $ids = $this->getListIds();//这个方法获取所有的内容,下面红字部分对应它的方法
   foreach($ids as $k=>$value){
    //echo $value['catid'];
    if(!file_exists(ROOT_PATH.'demo/')){//判断根目录下面有没有这个文件夹,如果没有则创建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;
  }

  //拿出需要静态化的页面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单页静态化
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;
}

以前用的那个生成静态页面每次都要执行PHP文件,然后才能生成,现在我写的这个就是由人控制的,想生成就生成,很方便,希望能给大家带来方便,祝大家工作愉快。

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn