这款生成静态页面的方法与其它的有一点不同,这是利用smarty模板引擎的fetch函数,由smarty解析的文件保存到一个变量,然后再利用fopen 创建文件,此方法不适合大数据量生成。
代码如下 |
复制代码 |
include('./www.phprm.com/smarty/smarty.class.php'); $smarty = new smarty(); $smarty->template_dir = "templates/"; $smarty->compile_dir = "templates_c/"; $smarty->left_delimiter = "<{"; $smarty->right_delimiter = "}>"; $db = mysql教程_connect('localhost','root',''); mysql_select_db('test'); mysql_query('set names "utf8"'); $result = mysql_query('select * from news'); while($row[] = mysql_fetch_array($result)){ $smarty->assign('news',$row); } //$smarty->display('smarty_html.html'); //以上不用写注释你都能看懂 //这里我们不显示他 //而是获得他 $content = $smarty->fetch('smarty_html.html'); //获得smarty替换都的模板文件内容也就是display之后的smarty_html.php的内容 /* 其实这一步就相当于这样 ob_start(); 开启缓冲区 $smarty->display('smarty_html.html'); $content = ob_get_contents(); 获得缓冲区内容 ob_end_claen;关闭缓冲区 */ makehtml('news.html',$content);//写入内容到news.html文件 echo '<a href="news.html">查看</a>'; //点击查看静态页面就生成成功了! //但是有个问题就是必须在当前页面才行 //比如你在另外一个php文件里$smarty->fetch('smarty_html.html'); //只能得到原本的模板文件内容,因为没有assign所以所有的模板变量都没替换 //生成了也是费的! function makehtml($file,$content){ $fp = fopen($file,'w'); fwrite($fp,$content); fclose($fp); } ?> |
//模板页面
代码如下 |
复制代码 |
<!doctype html public "-//w3c//dtd xhtml 1.0 transitional//en" "http://www.w3.org/tr/xhtml1/dtd/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8" /> <title>无标题文档</title> </head> <body> <{section name=n loop=$news}> id <{$news[n].news_id}><br /> title <{$news[n].news_title}> <br /> content<{$news[n].news_content}> <hr /> <{sectionelse}> 暂时没有新闻 <{/section}> </body> </html> |
永久地址:http://www.phprm.com/frame/34099.html
转载随意~请带上教程地址吧^^