当前位置: 首页 > 图文教程 > 网络编程 > PHP > php下把数组保存为文件格式的实例应用

PHP
PHP新手总结的PHP基础知识
php实现gb2312和unicode间编码转换
用php语言实现数据库连接详细代码介绍
详细解析 PHP 向 MySQL 发送数据过程
利用PHP V5开发多任务应用程序
详细讲解PHP中缓存技术的应用
php escapeshellcmd多字节编码漏洞
《PHP设计模式介绍》导言
《PHP设计模式介绍》第一章 编程惯用法
《PHP设计模式介绍》第二章 值对象模式
《PHP设计模式介绍》第三章 工厂模式
《PHP设计模式介绍》第四章 单件模式
《PHP设计模式介绍》第五章 注册模式
《PHP设计模式介绍》第六章 伪对象模式
《PHP设计模式介绍》第七章 策略模式
《PHP设计模式介绍》第八章 迭代器模式
《PHP设计模式介绍》第九章 观测模式
《PHP设计模式介绍》第十章 规范模式
《PHP设计模式介绍》第十一章 代理模式
《PHP设计模式介绍》第十二章 装饰器模式

PHP 中的 php下把数组保存为文件格式的实例应用


出处:互联网   整理: 软晨网(RuanChen.com)   发布: 2010-02-27   浏览: 187 ::
收藏到网摘: n/a

我们通常把一些常用的数据保存为数组格式方便调用,同时这也是缓存的重要方法。 我使用过两种办法:
第一种是数组序列化,简单,但是调用时比较麻烦一些;第二种是保存为标准的数组格式,保存时麻烦但是调用时简单。
第一种方法:
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;
}
}

调用方法很简单:
PHP代码
复制代码 代码如下:

cache_write('file', 'arrayName', $array);

使用上形同标准的include格式:
PHP代码
复制代码 代码如下:

@include ('./data/data_cache.php');
//数组重新排序
sort($arrayName);