开发者

PHP: Cache a tidy parsed string

At the top of my pa开发者_运维问答ge I have this piece of code to check cache and initiate 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();  
    }  

Then at the bottom I use this to tidy the output buffer and cache the page, but it nothing appears to be cached...

$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;

Anyone know what to do?


There were some errors in your code:

  • $cache_filename is a string, not an object
  • the $tiny()-object can't be simply put into a file - you need to take the value

I fixed them like so, taking the example of the 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;
?>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜