Home  >  Article  >  Backend Development  >  PHP动态变静态原理_php基础

PHP动态变静态原理_php基础

WBOY
WBOYOriginal
2016-05-17 09:43:46615browse

用PHP输出静态页面的方法,就我所知道的,有2种,一种是利用模板技术,另一种是用ob系列函数。两种方法,看起来都差不多,但是实际上,却是不同的。

第一种:利用模板。目前PHP的模板可以说是很多了,有功能强大的smarty,还有简单易用的smarttemplate等。它们每一种模板,都有一个获取输出内容的函数。我们生成静态页面的方法,就是利用了这个函数。用这个方法的优点是,代码比较清晰,可读性好。

这里我用smarty做例子,说明如何生成静态页

复制代码 代码如下:
require('smarty/Smarty.class.php'); 
$t = new Smarty; 
$t->assign("title","Hello World!"); 
$content = $t->fetch("templates/index.htm"); 
//这里的 fetch() 就是获取输出内容的函数,现在$content变量里面,就是要显示的内容了 
$fp = fopen("archives/2005/05/19/0001.html", "w"); 
fwrite($fp, $content); 
fclose($fp); 
?>  

第二种方法:利用ob系列的函数。这里用到的函数主要是 ob_start(), ob_end_flush(), ob_get_content(),其中ob_start()是打开浏览器缓冲区的意思,打开缓冲后,所有来自PHP程序的非文件头信息均不会发送,而是保存在内部缓冲区,直到你使用了ob_end_flush().而这里最重要的一个函数,就是ob_get_contents(),这个函数的作用是获取缓冲区的内容,相当于上面的那个fetch(),道理一样的。代码:
复制代码 代码如下:
ob_start(); 
echo "Hello World!"; 
$content = ob_get_contents();//取得php页面输出的全部内容 
$fp = fopen("archives/2005/05/19/0001.html", "w"); 
fwrite($fp, $content); 
fclose($fp); 
?>  
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn