Home > Backend Development > PHP Tutorial > How to save array to file format in php? Example code

How to save array to file format in php? Example code

WBOY
Release: 2016-07-25 08:52:17
Original
1017 people have browsed it
  1. $file="./cache/file.cache";
  2. $array = array("color" => array("blue", "red", "green"),
  3. "size" = > array("small", "medium", "large"));
  4. //Cache
  5. file_put_contents($file,serialize($array));//Write cache
  6. //Read cache
  7. $handle = fopen($file, "r");
  8. $cacheArray = unserialize(fread($handle, filesize ($file)));
Copy code

Second method:

Post a few functions first:

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

Call:

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

include format:

@include ('./data/data_cache.php'); //Array reordering sort($arrayName);


source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template