我想在我的网站上为我的php页面创建一个缓存。我确实找到了太多的解决方案,但我想要的是一个可以从我的数据库生成HTML页面的脚本:
我有一个类别页面可以抓取数据库中的所有类别,因此脚本应该能够生成排序的HTML页面:my-categories.html。然后,如果我选择一个类别,我应该得到一个my-x-category.html页面,依此类推,等等其他类别和子类别。
我可以看到一些网站的网址如下:wwww.the-web-site.com/the-page-ex.html
即使它们是动态的。
非常感谢你的帮助
答案 0 :(得分:8)
检查ob_start()函数
ob_start();
echo 'some_output';
$content = ob_get_contents();
ob_end_clean();
echo 'Content generated :'.$content;
答案 1 :(得分:4)
您可以使用网址重写获取此类网址。例如:对于apache,请参阅mod_rewrite
http://httpd.apache.org/docs/2.2/mod/mod_rewrite.html
您实际上并不需要创建文件。您可以创建文件,但它更复杂,因为您需要决定在数据更改时何时更新它们。
答案 2 :(得分:3)
手动缓存(创建HTML并将其保存到文件中)可能不是最有效的方法,但是如果你想沿着这条路走下去,我推荐以下内容(从我编写的一个简单的测试应用程序中删除) :
$cache_filename = basename($_SERVER['PHP_SELF']) . "?" . $_SERVER['QUERY_STRING'];
$cache_limit_in_mins = 60 * 32; // this forms 32hrs
// check if we have a cached file already
if ( file_exists($cache_filename) )
{
$secs_in_min = 60;
$diff_in_secs = (time() - ($secs_in_min * $cache_limit_in_mins)) - filemtime($cache_filename);
// check if the cached file is older than our limit
if ( $diff_in_secs < 0 )
{
// it isn't, so display it to the user and stop
print file_get_contents($cache_filename);
exit();
}
}
// create an array to hold your HTML output, this is where you generate your HTML
$output = array();
$output[] = '<table>';
$output[] = '<tr>';
// etc
// Save the output as manual cache
$file = fopen ( $cache_filename, 'w' );
fwrite ( $file, implode($output,'') );
fclose ( $file );
print implode($output,'');
答案 3 :(得分:2)
我使用APC进行所有PHP缓存(在Apache服务器上)
答案 4 :(得分:0)
如果您不反对框架,请尝试使用Zend Frameworks的Zend_Cache。它非常灵活,并且(与一些框架模块不同)易于实现。
答案 5 :(得分:0)
可以使用PEAR中的Cache_lite:
详情请点击此处 http://mahtonu.wordpress.com/2009/09/25/cache-php-output-for-high-traffic-websites-pear-cache_lite/
答案 6 :(得分:0)
我从数据库负载的角度思考,并对数据带宽和加载速度收费。我有一些页面不可能在几年内改变,(我知道使用基于数据库的CMS系统很容易)。与美国不同,这里的带宽成本可能很高。任何人都有任何意见,无论是创建页面还是动态(php,asp.net) 无论如何,页面的链接将存储在数据库中。
答案 7 :(得分:0)
在我看来,这是最好的解决方案。我将它用于我的Android App的缓存JSON文件。它可以简单地用在其他PHP文件中。 优化文件大小从~1mb到~163kb(gzip)。
cache
文件夹cache_start.php
文件并粘贴此代码<?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
并粘贴此代码<?php
$content = ob_get_contents();
ob_end_clean();
$file = fopen ( $cache_filename, 'w' );
fwrite ( $file, $content );
fclose ( $file );
echo gzencode($content);
?>
index.php
(要缓存的文件)<?php
include "cache_start.php";
echo "Hello Compress Cache World!";
include "cache_end.php";
?>