php生成html 伪静态??

mac2022-06-30  89

先建一个网页模板文件,命名为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文件,内容如下:     $con=array(array('新闻标题','新闻内容'),array('新闻标题2','新闻内容2'));  foreach($con as $id=>$val){  $title=$val[0];  $content=$val[1];  $path=$id.'.htm';  $fp=fopen("tmp.htm","r"); //只读打开模板  $str=fread($fp,filesize("tmp.htm"));//读取模板中内容  $str=str_replace("{title}",$title,$str);  $str=str_replace("{content}",$content,$str);//替换内容  fclose($fp);  $handle=fopen($path,"w"); //写入方式打开新闻路径  fwrite($handle,$str); //把刚才替换的内容写进生成的HTML文件  fclose($handle);  echo "生成成功";  } // unlink($path); //删除文件/ unlink($path); //删除文件  

 

<? php header ( "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.......

转载于:https://www.cnblogs.com/alex-13/p/3454338.html

相关资源:JAVA上百实例源码以及开源项目
最新回复(0)