PHP缓存页面的特定部分

5

我有一些需要大量资源的页面部分需要缓存,以下是页面示例。

[=== Some Static HTML ===]
[=== PHP Script 1 ===]
[=== Some Static HTML ===]
[=== PHP Script 2 ===]

我希望将"PHP Script 1"放入缓存文件中,例如script1.html,并包含它,而不是处理整个脚本,对于Script 2也是如此。但我遇到的问题是,虽然可以轻松地缓存整个页面并且可以正常工作,但我想只缓存特定部分(如上所述),因为某些内容,比如用户会话数据需要实时更新。
我有这个类,旨在能够停止和启动缓冲区,以便我可以提取特定部分而不破坏页面的其余部分,但它并没有做我想要的事情。 http://pastebin.com/Ua6DDExw 我希望能够像下面这样操作,同时将该部分存储在一个文件中,并使用简单的php include来调用,而不是直接从数据库中获取。
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或其他类似的东西的权限。

任何帮助都将不胜感激, 谢谢

1个回答

4

建议使用 ob_start()ob_flush(),这样可以实现您想要的功能。需要手动将其写入文件中。也可以在外部找到相关的cache.php类。

http://php.net/manual/zh/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.

谢谢,我会再做更多的研究。我一直很难理解所有不同的缓冲函数。 - Story Teller
2
试试这个教程,它会准确地讲解你想做的事情。http://www.mikebernat.com/blog/Caching_PHP_Pages_with_Output_Buffering - thenetimp
那个教程/脚本只有在我尝试缓存整个页面时才能起作用。请重新阅读我的问题。 - Story Teller
请检查我放在那里的代码,我不是说它在语法上是正确的,因为它很仓促,但你应该能够理解我的意思。 - thenetimp

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接