用php生成靜態文件的方式很簡單,就是用fopen()方法,fwrite(),fclose(),就好了,下面是php文檔中fopen中mode值的說明:
然后我們有一個需求就是在smarty模版引擎中點擊一個按鈕生成一個html的文件,內容是從數據庫讀出來的一串循環的、有層級的數據,這時候我們應該怎么做了?
用smarty生成靜態html文件的關鍵就是用緩存技術,開啟緩沖,用display或者fetch向前臺傳輸數據的時候其實不會顯示在view上,這時候打開文件,寫入文件,就生成好了一個靜態文件。
我們看2個實例:
1、
public function index() { $this->cismarty->caching = true; ob_start(); $title = "title"; $shopName = "穿越火線"; $model = '<li><h3>{#$shopName#}</h3></li>'; $outfilename = ".html"; $this->cismarty->assign("title", $title); $this->cismarty->assign("model", $model); $this->cismarty->assign("shopName", $shopName); $this->cismarty->display("ppms/smarty.html"); $str = ob_get_contents(); $fp = @fopen($outfilename, 'w'); if (!$fp) { Show_Error_Message( ERROR_WRITE_FILE ); } fwrite($fp, $str); fclose($fp); ob_end_clean(); }
2、
function makeHtml(){ ob_start(); $this->cismarty->assign("title","Hello World!"); $content = $this->cismarty->fetch("ppms/smarty.html"); //這里的 fetch() 就是獲取輸出內容的函數,現在$content變量里面,就是要顯示的內容了 $fp = fopen("0001.html", "w"); fwrite($fp, $content); fclose($fp); }
上面兩種方式是常用的,第一種用display方法,用$str = ob_get_contents();得到向前臺輸出的內容,第二種用fetch直接獲取向前臺輸出的內容(兩種都不會真正地展示出來中)。然后寫入到文件中,因為用“w”的方式,沒有這個文件就會新建一個。成功~~~
PHP編程鄭重聲明:本文版權歸原作者所有,轉載文章僅為傳播更多信息之目的,如作者信息標記有誤,請第一時間聯系我們修改或刪除,多謝。
新聞熱點
疑難解答