• 用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”的方式,没有这个文件就会新建一个。成功~~~

  • 相关阅读:
    JSP页面重定向与页面内容转发
    tomcat访问所有的资源,都是用Servlet来实现的
    War包是什么??
    jsp中include的两种用法
    TED #05# How we can face the future without fear, together
    TED #04#
    学写网页 #03# 固定在某个角落
    TED #03# 10 ways to have a better conversation
    TED #02#
    学写网页 #02# 无题
  • 原文地址:https://www.cnblogs.com/fredshare/p/2445898.html
Copyright © 2020-2023  润新知