PHP基础-生成静态html页面原理是怎样

本文介绍了一种使用PHP脚本来批量生成多个HTML页面的方法。通过设置一个包含文章标题和内容的数组,脚本能够根据一个模板文件example.html来生成article-1.html到article-5.html。文中还解释了如何利用fopen、fread、str_replace等函数实现这一过程。

设置example.html为模板文件,然后按照此模板文件生成article-1.html~article-5.html,以此来做简单的演示,代码如下:

<?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/>";

}?>}

注解:

fopen(文件名,打开方式),打开文件函数,若无文件,则创建。其返回值为资源型;

fread(文件名,读取字节数),读取文件内容及对应的字节数;

str_replace(规定要查找的值,替换被查找值的值,被搜索的字符串),替换函数;

fclose(文件名),关闭文件;

fwrite(要写入的打开文件,要写入打开文件的字符串,要写入的最大字节数)。

Andreas Creten explains his view on wether you should always try to write perfect code. Spoiler: no.

The engineers want to write perfect code using the latest techniques, make sure that the code is well documented so they can fully understand how everything works and that it has tests so they can easily update things later. Product owners on the other hand just want things to be done, fast and cheap, so they can ship new features or convince new clients.

How can you make these conflicting views work together?

https://medium.com/we-are-madewithlove/does-code-need-to-be-perfect-a53f36ad7163

Freek Van der Herten

Freek Van der Herten is a partner and developer at Spatie , an Antwerp based company that specializes in creating web apps with Laravel. After hours he writes about modernphp and Laravel on this blog. When not coding he’s probably rehearsing with his kraut rock band .

转载于:https://www.cnblogs.com/2881064178dinfeng/p/6145834.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值