使用 file_get_contents 创建 php 缓存

create php cache with file_get_contents

我正在尝试从一个菜单中创建一个缓存文件,该文件采用名为 '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);
}
?>

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

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

这一行

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);