PHP 部分缓存

标签 php caching

我想部分缓存一些 php 文件。例如

<?
echo "<h1>",$anyPerdefinedVarible,"</h1>";
echo "time at linux is: ";
// satrt not been catched section
echo date();
//end of partial cach
echo "<div>goodbye $footerVar</div>";
?>

所以缓存的页面应该像这样 (缓存.php)

<h1>This section is fixed today</h1>
<? echo date(); ?>
<div>goodbye please visit todays suggested website</div>

它可能是通过模板完成的,但我想要直接它。因为我想要替代解决方案。

最佳答案

看看php的ob_start(),它可以缓冲所有输出并保存它。 http://php.net/manual/en/function.ob-start.php

补充: 看http://www.php.net/manual/en/function.ob-start.php#106275对于你想要的功能:) 编辑: 这是一个更简单的版本:http://www.php.net/manual/en/function.ob-start.php#88212 :)


这里有一些简单但有效的解决方案:

模板.php

<?php
    echo '<p>Now is: <?php echo date("l, j F Y, H:i:s"); ?> and the weather is <strong><?php echo $weather; ?></strong></p>';
    echo "<p>Template is: " . date("l, j F Y, H:i:s") . "</p>";
    sleep(2); // wait for 2 seconds, as you can tell the difference then :-)
?>

实际页面.php

<?php    
    function get_include_contents($filename) {
        if (is_file($filename)) {
            ob_start();
            include $filename;
            return ob_get_clean();
        }
        return false;
    }

    // Variables
    $weather = "fine";

    // Evaluate the template (do NOT use user input in the template, look at php manual why)
    eval("?>" . get_include_contents("template.php"));
?>

您可以使用http://php.net/manual/en/function.file-put-contents.php保存template.php或actualpage.php的内容某些文件,例如cached.php。然后你可以让actualpage.php检查cached.php的日期,如果太旧,让它创建一个新的,或者如果足够年轻,只需回显actualpage.php或重新评估template.php而不重建模板。


评论后,这里缓存模板:

<?php    
    function get_include_contents($filename) {
        if (is_file($filename)) {
            ob_start();
            include $filename;
            return ob_get_clean();
        }
        return false;
    }

    file_put_contents("cachedir/cache.php", get_include_contents("template.php"));

?>

要运行此文件,您可以直接运行缓存的文件,也可以将其包含在其他页面上。喜欢:

<?php
    // Variables
    $weather = "fine";

    include("cachedir/cache.php");
?>

关于PHP 部分缓存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9968847/

相关文章:

Android HttpResponseCache 不工作 - FileNotFoundException

python - 在 Django 应用程序中实现 memcached 需要哪些步骤?

c# - MVC OutputCaching 是否优先于设置缓存响应 header ?

php - 尝试将数据发送到本地主机 :8000 from localhost 时 ajax 调用不起作用

javascript - 复选框输入的 bool 值

php - 使用 UTF-8 将 PHP 数组转换为 JSON 对象

HTTP If-None-Match 与 If-Match

php - Nginx 快速 CGI 缓存打开 error_page 404

php - 如何在 PHP 中将两个字符串组合在一起?

php - Jquery 选择器在附加后不起作用