PHP 缓存有几种方式
本人目前接触过两种缓存方式
1、全页面静态化缓存:
将页面全部生成为HTML静态页面,用户访问时直接访问静态页面,不走PHP服务器的解析流程,
实现方法:输出缓存
ob_start()--打开“输出控制缓冲”;
do some code --要运行的代码;
$content=ob_get_contents()--返回“输出缓冲区的内容”;
do some code --使用file_put_contents()等函数将返回的数据写入HTML文件;
ob_clearn()--清空“输出缓冲区”;
2、数据缓存
从数据库中取到数据后,数据缓存到一个php文件中(xxx.cache.php),在读取数据时,直接从cache中读取,不用每次都访问数据,这样能够提高数据访问速度。(适用于数据不经常变动的)
小例子:
<?php
header("Content-Type: text/html; charset=utf-8");
$cont = mysqli_connect('localhost','root','root','test');
if (!$cont) {
echo "连接失败!";
}
mysqli_set_charset($cont,'utf8');
$cache = array();
$sql = "select * from person";
$query = mysqli_query($cont,$sql);
while ($rs = mysqli_fetch_assoc($query)) {
$cache[$rs['id']] = $rs;
}
if ($cache) {
file_put_contents('./data/person.cache.php',"<?php\r\n $person_array =". sp_var_export($cache).";\r\n?>");
}
/*
* 函数名:sp_var_export
* 说 明:输出数组为代码格式
* 参 数:$input 要输出的数据 $indent 数组结果分隔符
* 返回值:代码格式的 数组
*/
function sp_var_export($input, $indent = '')
{
switch (gettype($input)) {
case 'string':
return "'" . str_replace(array(
"\\",
"'"
), array(
"\\\\",
"\'"
), $input) . "'";
case 'array':
$output = "array(\r\n";
foreach ($input as $key => $value) {
$output .= $indent . "\t" . sp_var_export($key, $indent . "\t") . ' => ' . sp_var_export($value, $indent . "\t");
$output .= ",\r\n";
}
$output .= $indent . ')';
return $output;
case 'boolean':
return $input ? 'true' : 'false';
case 'NULL':
return 'NULL';
case 'integer':
case 'double':
case 'float':
return "'" . (string) $input . "'";
}
return 'NULL';
}
?>
执行完以上代码会生成一个php文件,在界面访问数据时,可以从php文件中得到