标签:
php把数组保存为文件格式的函数实例,或许有的还没听说过可以把数组保存成文件,其实这样做也是另有它用的,两种方法各有千秋,有兴趣的PHP爱好者敬请参阅:
$file="./cache/file.cache";//定义要保存的数组文件路径、名称 $array = array("color" => array("blue", "red", "green"), "size" => array("small", "medium", "large")); file_put_contents($file,serialize($array));//写入缓存 //读取缓存 $handle = fopen($file, "r"); $cacheArray = unserialize(fread($handle, filesize ($file)));
下面是第二种方法,保存较麻烦,但调用很省事:
function cache_write($name, $var, $values) { $cachefile = S_ROOT.‘./data/data_‘.$name.‘.php‘; $cachetext = "<?php\r\n". "if(!defined(‘CHECK_CODE‘)) exit(‘Access Denied‘);\r\n". ‘$‘.$var.‘=‘.arrayeval($values). "\r\n?>"; if(!swritefile($cachefile, $cachetext)) { exit("File: $cachefile write error."); } } //数组转换成字串 function arrayeval($array, $level = 0) { $space = ‘‘; for($i = 0; $i <= $level; $i++) { $space .= "\t"; } $evaluate = "Array\n$space(\n"; $comma = $space; foreach($array as $key => $val) { $key = is_string($key) ? ‘\‘‘.addcslashes($key, ‘\‘\\‘).‘\‘‘ : $key; $val = !is_array($val) && (!preg_match("/^\-?\d+$/", $val) || strlen($val) > 12) ? ‘\‘‘.addcslashes($val, ‘\‘\\‘).‘\‘‘ : $val; if(is_array($val)) { $evaluate .= "$comma$key => ".arrayeval($val, $level + 1); } else { $evaluate .= "$comma$key => $val"; } $comma = ",\n$space"; } $evaluate .= "\n$space)"; return $evaluate; } //写入文件 function swritefile($filename, $writetext, $openmod=‘w‘) { if(@$fp = fopen($filename, $openmod)) { flock($fp, 2); fwrite($fp, $writetext); fclose($fp); return true; } else { runlog(‘error‘, "File: $filename write error."); return false; } }
复制以上代码为:data_cache.php文件,使用时include:
@include (‘data_cache.php‘); //数组重新排序 sort($arrayName);
调用方法:
cache_write(‘file‘,‘arrayName‘,$array);
标签:
原文地址:http://www.cnblogs.com/phpfensi/p/4333775.html