首页 > 语言 > PHP > 正文

把php生成静态(html)页面程序代码

2024-09-04 11:44:09
字体:大 中 小
来源:转载
供稿:网友

生成静态页面一般是把动态页面生成html页面,这样可以减少服务器负载也是现在各大网站常用的优化方法,下面我来分享一个把php生成静态(html)页面类.

  1. <?php 
  2.  
  3. class create_html { 
  4.  
  5. private $template; 
  6.  
  7. //模版 
  8.  
  9. private $file_name; 
  10.  
  11. //文件名 
  12.  
  13. private $array; 
  14.  
  15. //数据数组 
  16.  
  17. function __construct($file_name, $template, $array) { 
  18.  
  19. //构造类 
  20.  
  21. $this->template = $this->read_file($template, "r"); 
  22.  
  23. //读取模板文件 
  24.  
  25. $this->file_name = $file_name; 
  26.  
  27. $this->array = $array; 
  28.  
  29. //数据数据 
  30.  
  31. $this->html(); 
  32.  
  33. //生成html 
  34.  
  35. } 
  36.  
  37. function html() { 
  38.  
  39. //生成html 
  40.  
  41. while (ereg ("{([0-9]+)}", $this->template, $regs)) { 
  42.  
  43. //循环模版中所能的{1}….. 
  44.  
  45. $num = $regs[1]; 
  46.  
  47. //得到1、2、3序列 
  48.  
  49. $this->template = ereg_replace("{".$num."}", $this->array[$num], $this->template); 
  50.  
  51. //把数据替换成html内容 
  52.  
  53. $this->write_file($this->file_name, $this->template, "w+"); 
  54.  
  55. //生成HTML文件 
  56.  
  57. } 
  58.  
  59. } 
  60.  
  61. function read_file($file_url, $method = "r") { 
  62.  
  63. //读取文件 
  64.  
  65. $fp = @fopen($file_url, $method); 
  66.  
  67. //打开文件 
  68.  
  69. $file_data = fread($fp, filesize($file_url)); 
  70.  
  71. //读取文件信息 
  72.  
  73. return $file_data; 
  74.  
  75. } 
  76.  
  77. function write_file($file_url, $data, $method) { 
  78.  
  79. //写入文件 
  80.  
  81. $fp = @fopen($file_url, $method); 
  82.  
  83. //打开文件 
  84.  
  85. @flock($fp, LOCK_EX); 
  86.  
  87. //锁定文件 
  88.  
  89. $file_data = fwrite($fp, $data); 
  90.  
  91. //写入文件 
  92.  
  93. fclose($fp); 
  94.  
  95. //关闭文件 
  96.  
  97. return $file_data; 
  98.  
  99. } 
  100.  
  101. } 
  102.  
  103. #例子———————- 
  104.  
  105. #读取邮件回复模版———————————————————————————- 
  106.  
  107. $title = "标题"; 
  108.  
  109. $navigation = "浏览器"; 
  110.  
  111. $happy_origin = "作者"; 
  112.  
  113. $name = "test2.htm"; 
  114.  
  115. $template = "default_tmp.php"; 
  116.  
  117. //模版中用{1}{2}来替换 
  118.  
  119. $daytype = array(1 => $title, 
  120. //开源代码Vevb.com 
  121. 2 => $navigation, 
  122.  
  123. 3 => $happy_origin); 
  124.  
  125. $htm = new Restore_email($template, $daytype); 
  126.  
  127. echo $htm->pint(); 
  128.  
  129. ?> 

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表