先建一个网页模板文件,命名为tmp.html,内容如下:
<!DOCTYPE html><html><head><title> {title} </title><meta http-equiv = "Content-Type" content = "text/html; charset=UTF-8" ></head><body>{content}</body></html>
其中的{title}和{content}为将来要替换的内容
然后再建一个htm.php文件,用来生成html文件,内容如下:
<? phpheader ( "content-type:text/html; charset=utf-8" );$db = new mysqli ();$db -> connect ( "localhost" , "root" , "" , "news" );$db -> query ( "set names 'utf8'" );$sql = "select * from article order by id desc" ;$result = $db -> query ( $sql );while ( $row = $result -> fetch_array ()) {$title = $row [ 'title' ]; //从数据库中取出新闻标题存放到变量$title中$content = $row['content']; //从数据库中取出新闻内容存放到变量$content中$path = $row['id'] . ".html"; //根据新闻id来生成新闻路径$fp = fopen("tmp.html", "r"); //一只读方式打开模板文件$str = fread($fp, filesize("tmp.html")); //读取模板文件中的全部内容$str = str_replace("{title}", $title, $str); //用存储在变量$title中的新闻标题替换模板中的标题$str = str_replace("{content}", $content, $str); //用存储在变量$content中的新闻内容替换模板中的内容fclose($fp); //关闭模板文件$handle = fopen($path, "w"); //写入方式打开新闻路径fwrite($handle, $str); //把刚才替换的内容写入生成的html文件fclose($handle); //关闭文件}?>
执行htm.php文件,在该文件的目录中会生成和你的数据库中记录条数相同数量的html文件,其名称为1.html 2.html.......