Foreword
If every time a user clicks on a dynamic link, a data query request will be sent to the server. For a website with visits that may reach millions of levels, this will undoubtedly be a huge burden on the server, so the dynamic data Converting to a static HTML page has become the first choice to save manpower and material resources. Since I have no corresponding experience before, this article will share with you the principles and methods of using PHP to generate static HTML pages. If you need it, you can take a look together.
1. Idea analysis
In fact, the principle of realizing the static page generation function is very simple. It mainly uses several common PHP file operation functions to operate files. The idea process is as follows:
2. Function implementation
Set example.html as a template file, and then generate article-1.html~article-5.html according to this template file to make a simple demonstration. The code is as follows:
<?php //将数据存入二维数组 $con=array(array('文章标题1','文章内容1'),array('文章标题2','文章内容2'),array('文章标题3','文章内容3'),array('文章标题4','文章内容4'),array('文章标题5','文章内容5')); foreach($con as $id=>$val){ //循环生成 $title=$val[0]; $content=$val[1]; $path="article-".($id+1).".html"; //替换example内容,并获取内容赋值给$str $fp=fopen("example.html","r"); $str=fread($fp,filesize("example.html")); $str=str_replace("{title}",$title,$str); $str=str_replace("{content}",$content,$str); fclose($fp); //新建空白文件,将$str写入 $handle=fopen($path,"w"); fwrite($handle,$str); fclose($handle); echo "生成".$path."<br/>"; } ?> }
Note:
fopen (file name, open method), open file function, if there is no file, create it. The return value is resource type;
fread (file name, number of bytes to read), read the file content and the corresponding number of bytes;
str_replace (specifies the value to be found, replaces the value of the value being searched , the searched string), replacement function;
fclose(file name), close the file;
fwrite(the open file to be written, the string to be written to the open file, the maximum word to be written Section number).
3. Summary
The principle is relatively simple. As a PHP beginner, you must learn every basic knowledge well, and your PHP journey will be endless. The above is the entire content of this article. I hope it can be helpful to all PHP readers. Developers can help
For more related articles on the principles of using PHP to generate static html pages, please pay attention to the PHP Chinese website!