使用file_get_contents创建php缓存 [英] create php cache with file_get_contents

查看:218
本文介绍了使用file_get_contents创建php缓存的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to create a cache file from a menu that takes random data called 'includes/menu.php' the random data is created when I run that file manually, it works. Now I want to cache this data into a file for a certain amount of time and then recache it. I am running into 2 problems, from my code cache is created, but it caches the full php page, it does not cache the result, only the code without executing it. What am I doing wrong ? Here is what I have until now :

<?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文件并将结果保存到变量中):

will just read the php file, without executing it. Use this code instead (which will execute the php file and save the result into a variable):

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

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

And then, just save the retrieved content ($buffer) into file

file_put_contents($cache_file, $buffer);

这篇关于使用file_get_contents创建php缓存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆