php生成静态:PHP生成静态页来源: 发布时间:星期日, 2008年10月26日 浏览:152次 评论:0
PHP生成静态页
看到很多朋友在各个地方发帖问PHP生成静态文章系统的方法,以前曾做过这样一个系统,遂谈些看法,以供各位参考。好了,我们先回顾一些基本的概念。 一,PHP脚本与动态页面。 PHP脚本是一种服务器端脚本程序,可通过嵌入等方法与HTML文件混合,也可以类,函数封装等形式,以模板的方式对用户请求进行处理。无论以何种方式,它的基本原理是这样的。由客户端提出请求,请求某一页面 -----> WEB服务器引入指定相应脚本进行处理 -----> 脚本被载入服务器 -----> 由服务器指定的PHP解析器对脚本进行解析形成HTML语言形式 ----> 将解析后的HTML语句以包的方式传回给浏览器。由此不难看出,在页面发送到浏览器后,PHP就不存在了,已被转化解析为HTML语句。客户请求为一动态文件,事实上并没有真正的文件存在在那里,是PHP解析而成相对应的页面,然后发送回浏览器。这种页面处理方式被称为“动态页面”。 二,静态页面。 静态页面是指在服务器端确实存在的仅含HTML以及JS,CSS等客户端运行脚本的页面。它的处理方式是。由客户端提出请求,请求某一页面 ----> WEB服务器确认并载入某一页面 ----> WEB服务器将该页面以包的形式传递回浏览器。由这一过程,我们对比一下动态页面,即可方现。动态页面需由WEB服务器的PHP解析器进行解析,而且通常还需连接数据库,进行数据库存取操作,然后才能形成HTML语言信息包;而静态页面,无须解析,无须连接数据库,直接发送,可大大减轻服务器压力,提高服务器负载能力,大幅提供页面打开速度和网站整体打开速度。但其缺点是,不能动态地对请求进行处理,服务器上必须确实存在该文件。 三,模板及模板解析。 模板即尚未填充内容html文件。例如: temp.html <HTML> <TITLE>{ title }</TITLE> <BODY> this is a { file } file's templets </BODY> </HTML> PHP处理: templetest.php <?php $title = "落伍测试模板"; $file = "TwoMax Inter test templet,<br>author:Matrix@Two_Max"; $fp = fopen ("temp.html","r"); $content = fread ($fp,filesize ("temp.html")); $content .= str_replace ("{ file }",$file,$content); $content .= str_replace ("{ title }",$title,$content); echo $content; ?> 模板解析处理,即将经PHP脚本解析处理后得出的结果填充(content)进模板的处理过程。通常借助于模板类。目前较流行的模板解析类有phplib,smarty,fastsmarty等等。模板解析处理的原理通常为替换。也有些程序员习惯将判断,循环等处理放进模板文件中,用解析类处理,典型应用为block概念,简单来说即为一个循环处理。由PHP脚本指定循环次数,如何循环代入等,再由模板解析类具体实施这些操作。 好了,对比过静态页面与动态页面各自的优劣,现在我们就来说说,如何用PHP生成静态文件。 PHP生成静态页面并不是指PHP的动态解析,输出HTML页面,而是指用PHP创建HTML页面。同时因为HTML的不可写性,我们创建的HTML若有修改,则需删掉重新生成即可。(当然你也可以选择用正则进行修改,但个人认为那样做倒不如删掉重新生成来得快捷,有些得不偿失。) 言归正传。用过PHP文件操作函数的PHP FANS知道,PHP中有一个文件操作函数fopen,即打开文件。若文件不存在,则尝试创建。这即是PHP可以用来创建HTML文件的理论基础。只要用来存放HTML文件的文件夹有写权限(即权限定义0777),即可创建文件。(针对UNIX系统而言,Win系统无须考虑。)仍以上例为例,若我们修改最后一句,并指定在test目录下生成一个名为test.html的静态文件: <?php $title = "落伍测试模板"; $file = "TwoMax Inter test templet,<br>author:Matrix@Two_Max"; $fp = fopen ("temp.html","r"); $content = fread ($fp,filesize ("temp.html")); $content .= str_replace ("{file}",$file,$content); $content .= str_replace ("{title}",$title,$content); // echo $content; $filename = "test/test.html"; $handle = fopen ($filename,"w"); //打开文件指针,创建文件 /* 检查文件是否被创建且可写 */ if (!is_writable ($filename)){ die ("文件:".$filename."不可写,请检查其属性后重试!"); } if (!fwrite ($handle,$content)){ //将信息写入文件 die ("生成文件".$filename."失败!"); } fclose ($handle); //关闭指针 die ("创建文件".$filename."成功!"); ?> 实际应用中常见问题解决方案参考: 一,文章列表问题: 在数据库中创建字段,记录文件名,每生成一个文件,将自动生成的文件名存入数据库,对于推荐文章,只需指向存放静态文件的指定文件夹中的该页面即可。利用PHP操作处理文章列表,存为字符串,生成页面时替换此字符串即可。如,在页面中放置文章列表的表格加入标记{articletable},而在PHP处理文件中: <?php $title = "落伍测试模板"; $file = "TwoMax Inter test templet,<br>author:Matrix@Two_Max"; $fp = fopen ("temp.html","r"); $content = fread ($fp,filesize ("temp.html")); $content .= str_replace ("{file}",$file,$content); $content .= str_replace ("{title}",$title,$content); // 生成列表开始 $list = ''; $sql = "select id,title,filename from article"; $query = mysql_query ($sql); while ($result = mysql_fetch_array ($query)){ $list .= '<a href='.$root.$result['filename'].' target=_blank>'.$result['title'].'</a><br>'; } $content .= str_replace ("{articletable}",$list,$content); //生成列表结束 // echo $content; $filename = "test/test.html"; $handle = fopen ($filename,"w"); //打开文件指针,创建文件 /* 检查文件是否被创建且可写 */ if (!is_writable ($filename)){ die ("文件:".$filename."不可写,请检查其属性后重试!"); } if (!fwrite ($handle,$content)){ //将信息写入文件 die ("生成文件".$filename."失败!"); } fclose ($handle); //关闭指针 die ("创建文件".$filename."成功!"); ?> 二,分页问题。 如我们指定分页时,每页20篇。某子频道列表内文章经数据库查询为45条,则,首先我们通过查询得到如下参数:1,总页数;2,每页篇数。第二步,for ($i = 0; $i < allpages; $i++),页面元素获取,分析,文章生成,都在此循环中执行。不同的是,die ("创建文件".$filename."成功!";这句去掉,放到循环后的显示,因为该语句将中止程序执行。例: <?php $fp = fopen ("temp.html","r"); $content = fread ($fp,filesize ("temp.html")); $onepage = '20'; $sql = "select id from article where channel='$channelid'"; $query = mysql_query ($sql); $num = mysql_num_rows ($query); $allpages = ceil ($num / $onepage); for ($i = 0;$i<$allpages; $i++){ if ($i == 0){ $indexpath = "index.html"; } else { $indexpath = "index_".$i."html"; } $start = $i * $onepage; $list = ''; $sql_for_page = "select name,filename,title from article where channel='$channelid' limit $start,$onepage"; $query_for_page = mysql_query ($sql_for_page); while ($result = $query_for_page){ $list .= '<a href='.$root.$result['filename'].' target=_blank>'.$title.'</a><br>'; } $content = str_replace ("{articletable}",$list,$content); if (is_file ($indexpath)){ @unlink ($indexpath); //若文件已存在,则删除 } $handle = fopen ($indexpath,"w"); //打开文件指针,创建文件 /* 检查文件是否被创建且可写 */ if (!is_writable ($indexpath)){ echo "文件:".$indexpath."不可写,请检查其属性后重试!"; //修改为echo } if (!fwrite ($handle,$content)){ //将信息写入文件 echo "生成文件".$indexpath."失败!"; //修改为echo } fclose ($handle); //关闭指针 } fclose ($fp); die ("生成分页文件完成,如生成不完全,请检查文件权限系统后重新生成!"); ?> 大致思路如此,其中如其它数据生成,数据输入输出检查,分页内容指向等可酌情在页面中加入。 在实际文章系统处理过程当中,还有许多问题有待考虑,与动态页面不同之处,需注意的地方还有很多。但大致思路即是如此,其它方面可举一反三而得。 Asp.NET 生成静态页 环境:Microsoft .NET Framework SDK v1.1 OS:Windows Server 2003 中文版 ASP.Net生成静态HTML页 在Asp中实现的生成静态页用到的FileSystemObject对象! 在.Net中涉及此类操作的是System.IO 以下是程序代码 注:此代码非原创!参考别人代码 //生成HTML页 public static bool WriteFile(string strText,string strContent,string strAuthor) { string path = HttpContext.Current.Server.MapPath("/news/"); Encoding code = Encoding.GetEncoding("gb2312"); // 读取模板文件 string temp = HttpContext.Current.Server.MapPath("/news/text.html"); StreamReader sr=null; StreamWriter sw=null; string str=""; try { sr = new StreamReader(temp, code); str = sr.ReadToEnd(); // 读取文件 } catch(Exception exp) { HttpContext.Current.Response.Write(exp.Message); HttpContext.Current.Response.End(); sr.Close(); } string htmlfilename=DateTime.Now.ToString("yyyyMMddHHmmss")+".html"; // 替换内容 // 这时,模板文件已经读入到名称为str的变量中了 str =str.Replace("ShowArticle",strText); //模板页中的ShowArticle str = str.Replace("biaoti",strText); str = str.Replace("content",strContent); str = str.Replace("author",strAuthor); // 写文件 try { sw = new StreamWriter(path + htmlfilename , false, code); sw.Write(str); sw.Flush(); } catch(Exception ex) { HttpContext.Current.Response.Write(ex.Message); HttpContext.Current.Response.End(); } finally { sw.Close(); } return true; 此函数放在Conn.CS基类中了 在添加新闻的代码中引用 注:工程名为Hover if(Hover.Conn.WriteFilethis.Title.Text.ToString),this.Content.Text.ToString),this.Author.Text.ToString))) { Response.Write("添加成功"); } else { Response.Write("生成HTML出错!"); } 模板页Text.html代码 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" > <HTML> <HEAD> <title>ShowArticle</title> <body> biaoti <br> content<br> author </body> </HTML> biaoti <br> content<br> author </body> </HTML> 非摸板生成静态页 目前已经有很多生成html的新闻系统,但是都是用的模板,本函数实现把asp页面产生的html代码保存成为一个html文件,这样就没有必要改动原来的页面就可以轻松完成一个生成html的新闻系统了。^_^ 由于代码比较短,这里就不进行注释了 <% '当目标页面的包含文件即#include的页面里边存在response.End()的时候本程序有问题 '注意:本文件一定要放在filename指向的文件的同一目录下 dim hughchiu_rtcode Function get_exe_code(filename) dim execode dim tmp_str Dim re,re1,content,fso,f,aspStart,aspEnd dim ms,m execode = "" set fso=CreateObject("Scripting.FileSystemObject") set f=fso.OpenTextFile(server.mappath(filename)) c.ReadAll f.close set f=nothing set fso=nothing set re = new regexp re.ignorecase = true re.global = true re.pattern = "\<\%\@[^\%]+\%\>" content = re.replace(content,"") re.global = false re.pattern = "\<\!\-\-\s*\#include\s*file\s*=\s*\""([^\""]+)\""\s*\-\-\>" do set ms = re.execute(content) if ms.count<>0 then set m = ms(0) tmp_str = get_exe_code(m.submatches(0)) content = re.replace(content, tmp_str) else exit do end if loop set m = nothing set ms = nothing re.pattern="^\s*=" aspEnd=1 aspStart=inStr(aspEnd,content,"<%")+2 set re1=new RegExp re1.ignorecase = true re1.global = false re1.pattern = "response\.Write(.+)" do while aspStart>aspEnd+1 execode = execode&vbcrlf&" hughchiu_rtcode = hughchiu_rtcode&"""&replace( replace(Mid(content,aspEnd,aspStart-aspEnd-2),"""",""""""), vbcrlf, """&vbcrlf&""")&""""&vbcrlf aspEnd=inStr(aspStart,content,"%\>")+2 tmp_str = Mid(content,aspStart,aspEnd-aspStart-2) do set ms = re1.execute(tmp_str) if ms.count<>0 then set m = ms(0) tmp_str = re1.replace(tmp_str, " hughchiu_rtcode = hughchiu_rtcode&"&m.submatches(0)) else exit do end if loop set m = nothing set ms = nothing execode = execode& re.replace(tmp_str,"hughchiu_rtcode = hughchiu_rtcode&") aspStart=inStr(aspEnd,content,"<%")+2 loop set re1 = nothing set re=nothing execode = execode&vbcrlf&" hughchiu_rtcode = hughchiu_rtcode&"""&replace( replace(Mid(content,aspEnd), """", """"""), vbcrlf, """&vbcrlf&""" )&""""&vbcrlf get_exe_code = "<%"&execode&"%\>" End Function function asp2html(filename) dim code code = replace( replace( replace( get_exe_code(filename), "hughchiu_rtcode = hughchiu_rtcode&"""""&vbcrlf, "" ), "<%", "" ), "%\>", "" ) 'response.Write(code) execute(code) 'response.Write( hughchiu_rtcode ) asp2html = hughchiu_rtcode end function %> 0
相关文章
读者评论
发表评论 |