我认为这是最好的解决办法。我用这个为我的android应用程序缓存json文件。它可以简单地在其他php文件中使用。
它将文件大小从~1MB优化到~163KB(gzip)
.
创造
cache
目录中的文件夹
然后创建
cache_start.php
存档并粘贴此代码
header("HTTP/1.1 200 OK");
//header("Content-Type: application/json");
header("Content-Encoding: gzip");
$cache_filename = basename($_SERVER['PHP_SELF']) . "?" . $_SERVER['QUERY_STRING'];
$cache_filename = "./cache/".md5($cache_filename);
$cache_limit_in_mins = 60 * 60; // It's one hour
if (file_exists($cache_filename))
{
$secs_in_min = 60;
$diff_in_secs = (time() - ($secs_in_min * $cache_limit_in_mins)) - filemtime($cache_filename);
if ( $diff_in_secs < 0 )
{
print file_get_contents($cache_filename);
exit();
}
}
ob_start("ob_gzhandler");
?>
创造
cache_end.php
并粘贴此代码
$content = ob_get_contents();
ob_end_clean();
$file = fopen ( $cache_filename, 'w' );
fwrite ( $file, $content );
fclose ( $file );
echo gzencode($content);
?>
然后创建例如
index.php
(要缓存的文件)
include "cache_start.php";
echo "Hello Compress Cache World!";
include "cache_end.php";
?>