我正在寻找一个脚本,可以在运行时从动态内容生成静态HTML页面。我想要做的基本上是将这些生成的HTML页面缓存以供离线浏览。请问有人可以指点我正确的方向吗?谢谢。
static.php
:Hello, <a href="profile.php"><?php echo htmlspecialchars($username); ?></a>!
文件 functions.php
:
/**
* Renders cached page.
*
* @param string $template The dynamic page to cache.
* @param integer $uid The user ID (security precaution to prevent collisions).
* @param array $vars Set of variables passed to dynamic page.
*/
function cache_page($template, $uid, $vars)
{
$cache = 'cache/' . $uid . '-' . md5(@json_encode($vars)) . '.cache';
if (!file_exists($cache)) { // <- also maybe check creation time?
// set up template variables
extract($template_vars, EXTR_SKIP);
// start output buffering and render page
ob_start();
include $template;
// end output buffering and save data to cache file
file_put_contents($cache, ob_get_clean());
}
readfile($cache);
}
文件 index.php
:
require_once 'functions.php';
cache_page(
'static.php',
getUser()->id,
['username' => getUser()->username]
);
使用fopen函数将页面保存到本地以供离线阅读,但实际操作比听起来要棘手得多。