我正在使用Smarty和我的PHP代码,我喜欢缓存一些网站页面,所以我使用以下代码:
// TOP of script
ob_start(); // start the output buffer
$cachefile ="cache/cachefile.html";
// normal PHP script
$smarty->display('somefile.tpl.html') ;
$fp = fopen($cachefile, 'w'); // open the cache file for writing
fwrite($fp, ob_get_contents()); // save the contents of output buffer to the file
fclose($fp); // close the file
ob_end_flush(); // Send the output to the browser
但是当我在php文件的末尾打印ob_get_contents()时它是空的!实际上创建的缓存文件也是空的!所以当我使用smarty时,我怎么能在php中缓存文件我知道我可以使用smarty缓存但是由于某些原因它对我不起作用 .
另外请给我关于APC缓存的信息 . 如何使用它?是否值得在我的情况下使用,我瘦它只是为了缓存数据库查询,我阅读关于它的PHP手册但我不能得到任何东西:)坦克 .
2 回答
你的意思是你在调用ob_end_flush()后再次调用ob_get_contents()?如果是这样,您写入文件的内容将从PHP的内存中“删除” .
如果您仍希望输出HTML,请先将ob_end_flush保存到变量中,然后将其传递给fwrite . 您可以在页面后面使用该变量 .
我已经从文档中找到了一些代码(位于here),以获得更完整的智能缓存示例 . 另外,我'm not sure what you were using in your example, but you should be using smarty'的方法来操纵缓存 .
至于APC缓存,它的工作方式与smarty相同 . 它们都将数据存储在文件中一段特定的时间 . 每次要访问数据时,它都会检查缓存是否有效,如果是,则返回缓存值 .
但是,如果不使用smarty,您可以使用APC:
这个例子通过将数据库查询的结果存储在缓存中,类似地,您可以修改它来代替存储整个页面输出,这样您就不必经常运行昂贵的PHP函数 .
结合一些逻辑,
此示例稍微修改自here .