动态PHP内容,存储它并执行每日而不是每个页面加载?

时间:2011-08-26 14:20:31

标签: php

我希望回应一些使用php类从源代码收集的内容。没有其他方法可以获取此内容(这只是文本)。

现在内容不断变化,因此默认功能是在每次页面加载时访问并回显它,但是我宁愿每天更新一次,但每次页面加载时都会继续回显内容。

所以我的问题是类文件被编码因此我无法以这种方式进行更改。我希望我能创建一些能够存储文本并回显存储文本的东西,直到第二天它将运行原始函数来获取新内容。

收集和回忆内容的功能:

<?php showcontent($txtonly); ?>

我也不希望将内容放在文件中并获取内容。希望有人可以帮助我:))

4 个答案:

答案 0 :(得分:8)

从源中检索时,请写入文本文件。在每个页面加载时,检查该文件的年龄是否超过一天。如果是,请使用常规方法检索新内容并将其保存到文件中。如果它不是一天,只需读取本地缓存文件并输出它:

$cache_file = '/path/to/file.txt';

// Page was  requested....
// It's less than a day old, just output it.
if (file_exists($cache_file) && filemtime($cache_file) > time() - 86400) {
  echo file_get_contents($cache_file);
}
// It's older than a day, get the new content
else {
  // do whatever you need to get the content
  $content = whatever();

  // Save it into the cache file
  file_put_contents($cache_file, $content);
  // output the new content
  echo $content;
}

注意:您需要确保Web服务器可以写入存储缓存文件的目录。

答案 1 :(得分:3)

PHP不是你需要的“持久”。您可以在特定时间通过cron轻松运行PHP脚本来获取更改的数据,但您必须将该数据存储在某处,否则当此fetch脚本退出时它就会消失。最简单的方法就是使用文件。 fetch cript可以使用新数据覆盖它,而其他脚本只需在运行时包含/加载该文件,并在每次更改时自动获取新数据。

答案 2 :(得分:3)

您需要的是缓存组件。首先,您使用PHP的本机output control来捕获showcontent生成的任何内容...接下来,您每天将其存储在单独的文件中(像cache.php这样简单)。它可以像基于cron的脚本一样简单,该脚本在早上03:01运行,删除旧文件,并生成一个新文件。

示例生成脚本(每天调用一次)

<?php
$cache_file="cache.php";
$heredoc_sep="START_TO_END_12";//12 just a number to keep it unlikely change as you see fit (must not ever be in CONTENT below)

//Capture content
ob_start();
showcontent($txtonly);
$content=ob_get_contents();
ob_end_clean();

//Store in file
$fp=fopen($cache_file,"w");//Truncates to zero length
fwrite($fp,"<?php\necho <<<$heredoc_sep\n");
fwrite($fp,$content);
fwrite($fp,"$heredoc_sep;\n");
fclose($fp);
?>

现在使用结果,只需<?php include("cache.php");?>代替<?php showcontent($txtonly); ?>

答案 3 :(得分:2)

除了其他答案之外:如果您无法将编码类中的内容作为字符串获取,则可以使用PHP的output control functions,如下所示:

ob_start();
showcontent($txtonly);
$content = ob_get_clean();