生成html頁面我們需要使用到的文件系統(tǒng)操作函數(shù)包括有fopen,fread,filesize,fwrite,fclose了,這些是基本要用到了,還像刪除,創(chuàng)建目錄之類的,下面我們來看看.
1.PHP部分文件操作函數(shù)。(fopen , fread , filesize , fwrite , fclose)
2.unlink() , mkdir() 刪除函數(shù)。
1.PHP部分文件操作函數(shù)
(1)fopen 打開文件函數(shù)。 R / W / A
格式:fonpen(路徑和文件名,打開方式);
(2)fread 讀取文件內(nèi)容。
格式:fread(打開的文件,結(jié)束的位置);
(3)filesize 讀取文件大小,字節(jié)為計(jì)量單位。
格式:filesize(路徑和文件名);
(4)fwrite 寫入文件內(nèi)容。
格式:fwrite(路徑和文件名,寫入的內(nèi)容);
(5)fclose 關(guān)閉打開的文件。
格式:fclose(路徑和文件名);
2.unlink(); mkdir(); 刪除函數(shù)
unlink(); 刪除文件函數(shù)
格式:unlink(路徑和文件);
mkdir(); 刪除目錄函數(shù)
格式:mkdir(路徑和目錄名);
實(shí)例操作,代碼如下:
- <?php
- $title = "新標(biāo)題";
- $content = "新內(nèi)容m.survivalescaperooms.com";
- $fp = fopen("tmp.htm", "r"); //打開文件,以只讀方式。
- $str = fread($fp, filesize("tmp.htm")); //讀取文件內(nèi)容,格式:fread(打開的文件,結(jié)束的位置);。
- $str = str_replace("{title}", $title, $str); //將str變量中的路徑文件內(nèi)容替換掉重新賦值
- $str = str_replace("{content}", $content, $str);
- fclose($fp); //以上為替換模板的內(nèi)容。
- $id = "hello";
- $path = $id . '.htm';
- $handle = fopen($path, "w"); //寫入方式打開新聞路徑
- fwrite($handle, $str); //把剛才替換的內(nèi)容寫進(jìn)生成的HTML文件
- fclose($handle);
- echo "生成成功";
- ?>
例,找到一個(gè)html生成類,代碼如下:
- <?php
- // --------------------------------------------------------------------------
- // File name : html.class.php
- // Description : m.survivalescaperooms.com生成靜態(tài)頁面的類
- // Requirement : PHP5
- //
- // Copyright(C), 蟋蟀, 2013, All Rights Reserved.
- //--------------------------------------------------------------------------
- class myHtml{
- //生成html文件路徑
- private $html_dir="./";
- //html文件名稱
- private $html_name;
- //生成html文件的位置名稱
- public $path;
- //緩存區(qū)內(nèi)容
- private $content;
- //文件句柄
- private $handle;
- //內(nèi)存指針
- private $accesses;
- //構(gòu)造函數(shù)
- public function __construct($html_dir="",$html_name="")
- {
- $this->accesses++;
- //如果文件路徑不存在建立文件夾
- if(opendir($html_dir)==0)
- {
- mkdir($html_dir);
- }
- $this->html_dir=$html_dir!=""?$html_dir:"./";
- $this->html_name=$html_name!=""?$html_name:substr(basename(__FILE__),0,strrpos(basename(__FILE__),".")).".html";
- $this->path= ($this->html_dir{strlen($this->html_dir)-1}=="/")
- ?($this->html_dir.$this->html_name):($this->html_dir."/".$this->html_name);
- ob_start();
- }
- //析構(gòu)函數(shù)
- public function __destruct()
- {
- $this->accesses--;
- ob_end_clean();
- }
- //生成html頁面
- function tohtml()
- {
- $this->content=ob_get_contents();
- if (is_file ($this->path)){
- @unlink ($this->path);
- }
- $handle = fopen ($this->path,"w");
- if (!is_writable ($this->path)){
- return false;
- }
- if (!fwrite ($handle,$this->content)){
- return false;
- }
- fclose ($handle); //關(guān)閉指針
- return $this->path;
- }
- }
- /*
- $html=new myHtml("./","z.htm");
- print "靜態(tài)頁面程序";
- $html->tohtml();
- */
- ?>
新聞熱點(diǎn)
疑難解答