我在页面上有一些部分,这些部分需要大量我要缓存的资源,这是该页面的示例。
[=== Some Static HTML ===]
[=== PHP Script 1 ===]
[=== Some Static HTML ===]
[=== PHP Script 2 ===]
我想将“PHP脚本1”放入缓存文件(例如script1.html)中,并包含它而不是处理整个脚本,对于脚本2也是一样。
我的问题是我可以轻松地缓存整个页面并且可以正常工作,但是我想仅缓存特定的部分(如上所述),因为某些事件(例如用户 session 数据)需要实时存在。
我有一个旨在停止和启动缓冲区的类,因此我可以取出特定部分而不会破坏页面的其余部分,但是它不能满足我的要求。
http://pastebin.com/Ua6DDExw
我希望能够像下面这样,尽管它会将节存储在具有简单php inlcude的文件中,而不是访问数据库。
HTML Content
<?php
$cache->start_buffer("cache_name");
// PHP Script
$cache->end_buffer("cache_name");
?>
HTML Content
<?php
$cache->start_buffer("cache_name");
// PHP Script
$cache->end_buffer("cache_name");
?>
我无权访问Memcache或其他类似内容,因为这将在共享主机上进行。
任何帮助都会很棒,
谢谢
最佳答案
研究使用ob_start()
和ob_flush()
它可以完成您想要做的事情。您需要手动将其写入文件。也有狂放的cache.php类。
http://php.net/manual/en/function.ob-start.php
<?php
$cache_time = 3600; // Time in seconds to keep a page cached
$cache_folder = '/cache'; // Folder to store cached files (no trailing slash)
// Think outside the box the original said to use the URI instead use something else.
$cache_filename = $cache_folder.md5(",MyUniqueStringForMyCode"); // Location to lookup or store cached file
//Check to see if this file has already been cached
// If it has get and store the file creation time
$cache_created = (file_exists($cache_file_name)) ? filemtime($this->filename) : 0;
if ((time() - $cache_created) < $cache_time) {
$storedData = readCacheFile($cache_filename);
}
else
{
// Alternatively you can ignore the ob_start/get_contents/end_flush code
// and just call a function and store it directly to the variable.
// Start saving stuff
ob_start();
/** do your work here echoing data to the screen */
$storedData = ob_get_contents();
ob_end_flush();
// create the cachefile for the data.
createCacheFile($cache_filename);
}
// Do stuff with $storedData.
关于PHP缓存页面的特定部分,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/9206056/