文件获取内容-使用fileget_contents创建php缓存


file get contents - 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('includes/menu.php');

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

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

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

file_put_contents($cache_file, $buffer);

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

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