从动态Php页面生成HTML静态页面

5
我正在寻找一个脚本,可以在运行时从动态内容生成静态HTML页面。我想要做的基本上是将这些生成的HTML页面缓存以供离线浏览。请问有人可以指点我正确的方向吗?谢谢。

1
任何缓存类都可以做到这一点。你只需要适应它们以使用可读的输出文件名。(或者你想要但在问题中没有提到的任何东西。) - mario
2个回答

4
如果您想手动完成此操作,可以使用输出缓冲。例如:
文件 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]
);

0

使用fopen函数将页面保存到本地以供离线阅读,但实际操作比听起来要棘手得多。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接