zoukankan      html  css  js  c++  java
  • 用Smarty模板引擎生成静态HTML文件

    用php生成静态文件的方式很简单,就是用fopen()方法,fwrite(),fclose(),就好了,下面是php文档中fopen中mode值的说明:

    然后我们有一个需求就是在smarty模版引擎中点击一个按钮生成一个html的文件,内容是从数据库读出来的一串循环的、有层级的数据,这时候我们应该怎么做了?

    用smarty生成静态html文件的关键就是用缓存技术,开启缓冲,用display或者fetch向前台传输数据的时候其实不会显示在view上,这时候打开文件,写入文件,就生成好了一个静态文件。

    我们看2个实例:

    1、

    View Code
     1 public function index()
     2     {
     3          $this->cismarty->caching = true;
     4          ob_start();
     5          $title = "title";
     6          $shopName = "穿越火线";
     7          $model = '<li><h3>{#$shopName#}</h3></li>';
     8          $outfilename = "0005.html";
     9          $this->cismarty->assign("title", $title);
    10          $this->cismarty->assign("model", $model);
    11          $this->cismarty->assign("shopName", $shopName);
    12          $this->cismarty->display("ppms/smarty.html"); 
    13          $str = ob_get_contents();
    14          $fp = @fopen($outfilename, 'w');
    15          if (!$fp) {
    16              Show_Error_Message( ERROR_WRITE_FILE );
    17          }
    18          fwrite($fp, $str);
    19          fclose($fp);
    20          ob_end_clean();
    21              
    22     }

    2、

    View Code
    1 function makeHtml(){
    2         ob_start();
    3         $this->cismarty->assign("title","Hello World!");
    4         $content = $this->cismarty->fetch("ppms/smarty.html");
    5         //这里的 fetch() 就是获取输出内容的函数,现在$content变量里面,就是要显示的内容了
    6         $fp = fopen("0001.html", "w");
    7         fwrite($fp, $content);        
    8         fclose($fp);    
    9 }

    上面两种方式是常用的,第一种用display方法,用$str = ob_get_contents();得到向前台输出的内容,第二种用fetch直接获取向前台输出的内容(两种都不会真正地展示出来中)。然后写入到文件中,因为用“w”的方式,没有这个文件就会新建一个。成功~~~

  • 相关阅读:
    【转】 springBoot(5)---单元测试,全局异常
    【转】 springBoot(4)---热部署,配置文件使用
    【转】 springBoot(3)---目录结构,文件上传
    【转】 springBoot(2)---快速创建项目,初解jackson
    【转】 springBoot(1)---springboot初步理解
    【转】 SpringBoot+MyBatis+MySQL读写分离
    简单请求 vs 非简单请求
    H5新增的API
    图片
    vue更新dom的diff算法
  • 原文地址:https://www.cnblogs.com/fredshare/p/2445898.html
Copyright © 2011-2022 走看看