PHP缓存页面的特定部分

Sto*_*ler 5 php caching

我在页面上有一些部分需要相当多的资源我想要缓存,这里是一个页面示例.

[=== Some Static HTML ===]
[=== PHP Script 1 ===]
[=== Some Static HTML ===]
[=== PHP Script 2 ===]
Run Code Online (Sandbox Code Playgroud)

我想将"PHP脚本1"放入缓存文件,例如script1.html并包含它而不是处理整个脚本,对于脚本2也是如此.

我遇到的问题是我可以轻松地缓存整个页面并且它可以工作,但我想只缓存特定部分(如上所述),因为有些事情需要用户会话数据.

我有这个类,意味着能够停止和启动缓冲区,所以我可以拉出特定的部分,而不会破坏页面的其余部分,但它不能做我想要的. 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");
?>
Run Code Online (Sandbox Code Playgroud)

我没有访问memcache或其他任何类似的东西,因为这将是共享主机.

任何帮助都会很棒,谢谢

the*_*imp 4

考虑使用它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.
Run Code Online (Sandbox Code Playgroud)

  • 试试这个教程,它准确地解释了你想要做什么。http://www.mikebernat.com/blog/Caching_PHP_Pages_with_Output_Buffering (2认同)