PHP:缓存一个整洁的解析字符串

时间:2011-08-19 08:40:44

标签: php outputcache output-buffering

在我的页面顶部,我有这段代码来检查缓存并启动输出缓冲:

ob_start( );
    $cache_time = 3600; 
    $cache_folder = $_SERVER['DOCUMENT_ROOT'].'/cache'; 
    $cache_filename = $cache_folder.md5($_SERVER['REQUEST_URI']);
    $cache_created  = (file_exists($cache_filename)) ? filemtime($cache_filename->filename) : 0;  

    if ((time() - $cache_created) < $cache_time) {  
      readfile($cache_filename); 
      die();  
    }  

然后在底部我使用它来整理输出缓冲区并缓存页面,但它似乎没有任何缓存......

$html = ob_get_clean();
$config = array('indent' => TRUE,
                'drop-empty-paras' => FALSE,
                'output-xhtml' => TRUE,
                'quote-ampersand' => TRUE,
                'indent-cdata' => TRUE,
                'tidy-mark' => FALSE,
                'wrap' => 200);
$tidy = tidy_parse_string($html, $config, 'UTF8');
file_put_contents($cache_filename, $tidy);
echo $tidy;

任何人都知道该怎么做?

1 个答案:

答案 0 :(得分:0)

您的代码中存在一些错误:

  • $ cache_filename是一个字符串,而不是一个对象
  • $ tiny() - 对象不能简单地放入文件中 - 您需要取值

我这样修理它们,以php manual page

为例
<?php
    $cache_time = 10; 
    $cache_folder = '/tmp/'; 
    $cache_filename = $cache_folder.md5($_SERVER['REQUEST_URI']);
    $cache_created  = (file_exists($cache_filename)) ? filemtime($cache_filename) : 0;  
    var_dump(time() - $cache_created);
    if ((time() - $cache_created) < $cache_time) {  
      readfile($cache_filename); 
      exit();  
    } 
?>

<?php
ob_start();
?>

<html>
  <head>
   <title>test</title>
  </head>
  <body>
   <p>error<br>another line</i>
  </body>
</html>

<?php

$buffer = ob_get_clean();
$config = array('indent' => TRUE,
                'output-xhtml' => TRUE,
                'wrap' => 200);

$tidy = tidy_parse_string($buffer, $config, 'UTF8');

$tidy->cleanRepair();
file_put_contents($cache_filename, $tidy->value);
echo $tidy;
?>