php静态缓存学习-2.使用模板文件生成静态html

使用模板文件生成静态页面做缓存的简单demo,可保存代码直接运行.cache文件夹没做创建,需手动先创建目录。
1.index.php

<?php
$cache_file = './cache/index.html';
if (is_file($cache_file) && (time() - filemtime($cache_file)) < 5) {
    //5秒更新一次页面
    require_once($cache_file);
} else {
    $title = '测试页面';
    $test = '这是我的测试页面' . date('Y-m-d H:i:s');
    $data = array(
        'title' => $title,
        'test' => $test
    );
    get_page_content('./index.html', $data, $cache_file);
}

/**
 * @param $template_file 模板文件 $data 需要传入模板的数据 $cache_file 缓存的文件
 */
function get_page_content($template_file, $data, $cache_file) {
    $fp = fopen($template_file, "r");//只读模式打开模板文件
    $template_content = fread($fp, filesize($template_file));//获取模板文件内容
    fclose($fp);//关闭

    foreach ($data as $key => $value) {//将传入的参数与模板变量语言进行替换
        $template_content = str_replace('{$' . $key . '}', $value, $template_content);
    }
    echo $template_content;//显示静态页面

    $handle = fopen($cache_file, "w");//写方式打开缓存文件
    fwrite($handle, $template_content);//将替换好的字符串写入页面
    fclose($handle);//关闭
}

2.index.html

<!Doctype html>
<html>
<head>
    <meta charset="utf-8">
    <title>{$title}</title>
</head>
<body>{$test}</body>
</html>

猜你喜欢

转载自blog.csdn.net/onlyjin/article/details/78665609
今日推荐