php生成HTML文件的应用和原理笔记
生成html页面我们需要使用到的文件系统操作函数包括有fopen,fread,filesize,fwrite,fclose了,这些是基本要用到了,还像删除,创建目录之类的,下面我们来看看.
1.PHP部分文件操作函数。(fopen , fread , filesize , fwrite , fclose)
2.unlink() , mkdir() 删除函数。
1.PHP部分文件操作函数
(1)fopen 打开文件函数。 R / W / A
格式:fonpen(路径和文件名,打开方式);
(2)fread 读取文件内容。
格式:fread(打开的文件,结束的位置);
(3)filesize 读取文件大小,字节为计量单位。
格式:filesize(路径和文件名);
(4)fwrite 写入文件内容。
格式:fwrite(路径和文件名,写入的内容);
(5)fclose 关闭打开的文件。
格式:fclose(路径和文件名);
2.unlink(); mkdir(); 删除函数
unlink(); 删除文件函数
格式:unlink(路径和文件);
mkdir(); 删除目录函数
格式:mkdir(路径和目录名);
实例操作,代码如下:
<?php $title = "新标题"; $content = "新内容www.phprm.com"; $fp = fopen("tmp.htm", "r"); //打开文件,以只读方式。 $str = fread($fp, filesize("tmp.htm")); //读取文件内容,格式:fread(打开的文件,结束的位置);。 $str = str_replace("{title}", $title, $str); //将str变量中的路径文件内容替换掉重新赋值 $str = str_replace("{content}", $content, $str); fclose($fp); //以上为替换模板的内容。 $id = "hello"; $path = $id . '.htm'; $handle = fopen($path, "w"); //写入方式打开新闻路径 fwrite($handle, $str); //把刚才替换的内容写进生成的HTML文件 fclose($handle); echo "生成成功"; ?>
例,找到一个html生成类,代码如下:
<?php // -------------------------------------------------------------------------- // File name : html.class.php // Description : www.phprm.com生成静态页面的类 // Requirement : PHP5 // // Copyright(C), 蟋蟀, 2013, All Rights Reserved. //-------------------------------------------------------------------------- class myHtml { //生成html文件路径 private $html_dir = "./"; //html文件名称 private $html_name; //生成html文件的位置名称 public $path; //缓存区内容 private $content; //文件句柄 private $handle; //内存指针 private $accesses; //构造函数 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(); } //析构函数 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); //关闭指针 return $this->path; } } /* $html=new myHtml("./","z.htm"); print "静态页面程序"; $html->tohtml(); */ ?>
本文地址:http://www.phprm.com/develop/fs1558.html
转载随意,但请附上文章地址:-)