【问题标题】:create php cache with file_get_contents使用 file_get_contents 创建 php 缓存
【发布时间】:2015-09-13 19:54:05
【问题描述】:

我正在尝试从一个名为“includes/menu.php”的随机数据的菜单中创建一个缓存文件,当我手动运行该文件时会创建随机数据,它可以工作。现在我想将这些数据缓存到一个文件中一段时间​​,然后重新缓存它。我遇到了 2 个问题,从我的代码缓存中创建,但它缓存了整个 php 页面,它不缓存结果,只缓存代码而不执行它。我究竟做错了什么 ?这是我到目前为止所拥有的:

<?php
$cache_file = 'cachemenu/content.cache';
if(file_exists($cache_file)) {
  if(time() - filemtime($cache_file) > 86400) {
     // too old , re-fetch
     $cache = file_get_contents('includes/menu.php');
     file_put_contents($cache_file, $cache);
  } else {
     // cache is still fresh
  }
} else {
  // no cache, create one
  $cache = file_get_contents('includes/menu.php');
  file_put_contents($cache_file, $cache);
}
?>

【问题讨论】:

标签: php file-get-contents file-put-contents


【解决方案1】:

这一行

file_get_contents('includes/menu.php');

只会读取 php 文件,而不执行它。请改用此代码(它将执行 php 文件并将结果保存到变量中):

ob_start();
include 'includes/menu.php';
$buffer = ob_get_clean();

然后,只需将检索到的内容($buffer)保存到文件中

file_put_contents($cache_file, $buffer);

【讨论】:

    【解决方案2】:

    file_get_contents() 获取文件的内容,它不会以任何方式执行它。 include() 将执行 PHP,但您必须使用输出缓冲区来获取其输出。

    ob_start();
    include('includes/menu.php');
    $cache = ob_get_flush();
    file_put_contents($cache_file, $cache);
    

    【讨论】:

    • ob_get_clean 也可能对您有用。 flush 将输出它并缓存它,而clean 不会输出它 - 你必须根据需要自己回显它。
    猜你喜欢
    • 2013-08-08
    • 2012-07-27
    • 1970-01-01
    • 2013-12-22
    • 2011-07-28
    • 2012-06-02
    • 2013-01-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多