1. 序列化缓存
a) Serialize 序列化(串行化)
b) Unserialize 反序列化(反串行化)
2. JSON数据缓存
a) Json_encode 数组转json字符串
b) Json_decode 字符串转数组
Json_decode($str,true)//当该参数为 TRUE 时 将返回 array 而非 object
3. XML数据缓存
a) 循环遍历组装产生xml字符串
b) Simplexml_load_string 将xml字符串转换回对象
4. 数组缓存
a) var_export($data,true)
b) Include/require
<?php
//该方式为数组缓存
$cache_dir = "./cache";
$cache_lifetime =10; //设置缓存生命周期
$cache_name = "cache.php";
$start = microtime(true);
if(file_exists($cache_dir."/".$cache_name) && time()-filemtime($cache_dir."/".$cache_name)<=$cache_lifetime){
$data = require once ($cache_dir."/".$cache_name);
}else{
try{
$pdo = new PDO("mysql:host=localhost;dbname=three","root","root",array(PDO::ATTR_ERRMODE=>PDO::ERRMODE_EXCEPTION));
$pdo->query("set names utf8");
$st = $pdo->prepare("select id,username,rtime,rip from t1");
$st->execute();
$data = $st->fetchAll(PDO::FETCH_ASSOC);
$arr = var_export($data,true);//转化成无语法错误的数组
//产生cache.php中形成 <?php
// return ....balalala
file_put_contents($cache_dir."/".$cache_name,"<?php\nreturn ".$arr."\n?>");
}catch(PDOException $e){
echo $e->getMessage();
}
}
$end = microtime(true);
echo "<table>";
echo "<tr>";
echo "<th>ID</th>";
echo "<th>USERNAME</th>";
echo "<th>RTIME</th>";
echo "<th>RIP</th>";
echo "<tr>";
foreach($data as $d){
echo "<tr>";
echo "<td>".$d['id']."</td>";
echo "<td>".$d['username']."</td>";
echo "<td>".$d['rtime']."</td>";
echo "<td>".$d['rip']."</td>";
echo "</tr>";
}
echo "</table>";
echo "time:".($end-$start);//测试时间
a) Serialize 序列化(串行化)
b) Unserialize 反序列化(反串行化)
2. JSON数据缓存
a) Json_encode 数组转json字符串
b) Json_decode 字符串转数组
Json_decode($str,true)//当该参数为 TRUE 时 将返回 array 而非 object
3. XML数据缓存
a) 循环遍历组装产生xml字符串
b) Simplexml_load_string 将xml字符串转换回对象
4. 数组缓存
a) var_export($data,true)
b) Include/require
<?php
//该方式为数组缓存
$cache_dir = "./cache";
$cache_lifetime =10; //设置缓存生命周期
$cache_name = "cache.php";
$start = microtime(true);
if(file_exists($cache_dir."/".$cache_name) && time()-filemtime($cache_dir."/".$cache_name)<=$cache_lifetime){
$data = require once ($cache_dir."/".$cache_name);
}else{
try{
$pdo = new PDO("mysql:host=localhost;dbname=three","root","root",array(PDO::ATTR_ERRMODE=>PDO::ERRMODE_EXCEPTION));
$pdo->query("set names utf8");
$st = $pdo->prepare("select id,username,rtime,rip from t1");
$st->execute();
$data = $st->fetchAll(PDO::FETCH_ASSOC);
$arr = var_export($data,true);//转化成无语法错误的数组
//产生cache.php中形成 <?php
// return ....balalala
file_put_contents($cache_dir."/".$cache_name,"<?php\nreturn ".$arr."\n?>");
}catch(PDOException $e){
echo $e->getMessage();
}
}
$end = microtime(true);
echo "<table>";
echo "<tr>";
echo "<th>ID</th>";
echo "<th>USERNAME</th>";
echo "<th>RTIME</th>";
echo "<th>RIP</th>";
echo "<tr>";
foreach($data as $d){
echo "<tr>";
echo "<td>".$d['id']."</td>";
echo "<td>".$d['username']."</td>";
echo "<td>".$d['rtime']."</td>";
echo "<td>".$d['rip']."</td>";
echo "</tr>";
}
echo "</table>";
echo "time:".($end-$start);//测试时间