首页  >  文章  >  后端开发  >  php怎么把数组保存为文件格式?实例代码

php怎么把数组保存为文件格式?实例代码

WBOY
WBOY原创
2016-07-25 08:52:171000浏览
  1. $file="./cache/file.cache";
  2. $array = array("color" => array("blue", "red", "green"),
  3. "size" => array("small", "medium", "large"));
  4. //缓存
  5. file_put_contents($file,serialize($array));//写入缓存
  6. //读出缓存
  7. $handle = fopen($file, "r");
  8. $cacheArray = unserialize(fread($handle, filesize ($file)));
复制代码

第二种方法:

先贴几个函数:

  1. //写入
  2. function cache_write($name, $var, $values) {
  3. $cachefile = S_ROOT.'./data/data_'.$name.'.php';
  4. $cachetext = " "if(!defined('CHECK_CODE')) exit('Access Denied');\r\n".
  5. '$'.$var.'='.arrayeval($values).
  6. "\r\n?>";
  7. if(!swritefile($cachefile, $cachetext)) {
  8. exit("File: $cachefile write error.");
  9. }
  10. }
  11. //数组转换成字串
  12. function arrayeval($array, $level = 0) {
  13. $space = '';
  14. for($i = 0; $i $space .= "\t";
  15. }
  16. $evaluate = "Array\n$space(\n";
  17. $comma = $space;
  18. foreach($array as $key => $val) {
  19. $key = is_string($key) ? '\''.addcslashes($key, '\'\\').'\'' : $key;
  20. $val = !is_array($val) && (!preg_match("/^\-?\d+$/", $val) || strlen($val) > 12) ? '\''.addcslashes($val, '\'\\').'\'' : $val;
  21. if(is_array($val)) {
  22. $evaluate .= "$comma$key => ".arrayeval($val, $level + 1);
  23. } else {
  24. $evaluate .= "$comma$key => $val";
  25. }
  26. $comma = ",\n$space";
  27. }
  28. $evaluate .= "\n$space)";
  29. return $evaluate;
  30. }
  31. //写入文件
  32. function swritefile($filename, $writetext, $openmod='w') {
  33. if(@$fp = fopen($filename, $openmod)) {
  34. flock($fp, 2);
  35. fwrite($fp, $writetext);
  36. fclose($fp);
  37. return true;
  38. } else {
  39. runlog('error', "File: $filename write error.");
  40. return false;
  41. }
  42. }
复制代码

调用:

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

include格式:

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


声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn