php 模板替换实现静态页面简单代码实现

来源:互联网 发布:盛发软件 编辑:程序博客网 时间:2024/05/18 07:31

1.处理页面

<?php
header("content-type:text/html;charset=utf8");
//连接数据库    
$pdo=new PDO("mysql:host=localhost;dbname=exam",'root','root');
$pdo->exec("set names utf8");
if ($_POST) {
    $title=$_POST['title'];
    $content=$_POST['content'];
    $arr=$pdo->exec("insert into newss(title,content) values('$title','$content')");
    //获得模版文件  网页的形式
    $str=file_get_contents("mo.htm");
    //echo $str;
    //替换内容
    $str=str_replace('{$title}',$title,$str);
    $str=str_replace('{$content}',$content,$str);
    //生成静态页面
    $id=$pdo->lastInsertId();
    $filename=$id.".html";
    file_put_contents('momo/'.$filename,$str);
} else {
    include "a.html";
}

?>

访问模板页面

<?php
header("content-type:text/html;charset=utf8");
//连接数据库    
$pdo=new PDO("mysql:host=localhost;dbname=exam",'root','root');
$pdo->exec("set names utf8");
$arr=$pdo->query("select * from newss")->fetchAll(PDO::FETCH_ASSOC);
?>
<table border="1">
    <tr>
        <td>编号</td>
        <td>标题</td>
    </tr>
    <?php foreach ($arr as $ke => $v) { ?>
    <tr>
        <td><?php echo  $v['id']  ?></td>
        <td><a href="momo/<?php echo $v['id'] ?>.html"><?php echo  $v['title']  ?></a></td>
    </tr>
    <?php  }  ?>
</table>

0 0