Maison  >  Article  >  développement back-end  >  PHP批量生成静态HTML的简单原理和方法

PHP批量生成静态HTML的简单原理和方法

高洛峰
高洛峰original
2016-12-21 11:15:271104parcourir

现在的CMS基本上都支持文章生成HTML,生成HTML静态网页的好处就不用多说了吧,无论是页面打开的浏览速度,还是有利于搜索引擎优化SEO,都有明显的提高,有时候网页中有或多或少的漏洞,把PHP转换成HTML格式也有力地保护了网站。

PHP生成HTML的技术要比ASP的技术相对来说要简单一点,下面简要说一下怎样用PHP批量生成HTML技术吧,先看一下面源码:

<?php   
if($_POST[button]){   

$sql="select * from doorsjk_about where id<12";   
$rs=$db->query($sql);   
while($row=$db->fetch_array($rs)){   

$path=&#39;list12&#39;.$row[id].&#39;.html&#39;;   

$fp=fopen("../group/about.html","r");   
$str=fread($fp,filesize("../group/about.html"));   
$str=str_replace("{title}",$row[title],$str);   
$str=str_replace("{name}",$system[&#39;name&#39;],$str);   
$str=str_replace("{content}",$row[content],$str);   
$str=str_replace("{copyright}",$system[&#39;copyright&#39;],$str);   
fclose($fp);   

$handle=fopen("../group/".$path,"w");    
fwrite($handle,$str);   
echo "<font color=&#39;red&#39;>正在生成</font>";   
echo "$path";   
fclose($handle);   
}   
echo "<script>alert(&#39;生成成功!&#39;);window.location.href=&#39;Onlyhtml.php&#39;;</script>";   
}   
?>   

<form id="form1" name="form1" method="post" action="">   
  <label><div style="margin:200px 200px;"><img src="../images/html.jpg" />   
  <input type="submit" name="button" id="button" value="单页生成" />   
  </div>   
  </label>   
</form>

首先将连接数据库的代码包含进来,下面是一个点击的表单,当接受到按钮 button 后,就直接循环生成HTML,这里的$path='list12′.$row[id].'.html';是生成的文件名称,而$fp=fopen(“../group/about.html”,”r”);是打开的模板文件,只要做成自己想要的HTML文件就可以了,这里用str_replace函数来做替换的标签,这样就可以在HTML里面调用类似于{title}这样的标签生成HTML文件了,举一反三,简单的HTML批量生成就做成了。

在HTML文件里调用标签是:{title} ,这样就直接调到读取的数据库里文件:$row[title],如果数据量很大,可以分段批量生成,就是生成ID:从()到()之间。用limit来接受调用。至于HTML里面要用到的动态文件,比如生成静态后还要统计文章的读取次数,这个动态的调用可以封装成JS文件,嵌入进来就行了。

080742450.jpg

这里介绍的是批量重新生成,其实还有在填加新闻时就生成HTML文件,编辑文章内容时生成HTML文件,其实原理上都差不多,我会写下来,可以做个参考。


更多PHP批量生成静态HTML的简单原理和方法相关文章请关注PHP中文网!


Déclaration:
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn