A variable in the form of a PHP cache array, in effect, is simply to write the array to a text file or a suffix named. php to store it, and call this file directly when used. So how do you use PHP to save the array as a text-formatted file? Here's a three-way implementation that writes a PHP array to a file to cache the array.
(1) using Serialize to store array serialization as a text file, and then use Unserialize to restore
<?php
$file = './cache/phone.php ';
$array =array (' Color ' => array (' Blue ', ' red ', ' green '), ' size ' => array (' small ', ' medium ', ' large '));
Cache
if (False!==fopen ($file, ' w+ ')) {
file_put_contents ($file, serialize ($array));/write Cache
}
//read out cache
$handle =fopen ($file, ' R ');
$cacheArray =unserialize (Fread ($handle, FileSize ($file));
(2) Self-created to save the array as a standard array format, although the save time is complex, but the call is simple
<?php $file = './cache/phone.php ';
$array =array (' Color ' => array (' Blue ', ' red ', ' green '), ' size ' => array (' small ', ' medium ', ' large '));
Cache_write ($file, $array, ' rows ', false);
Write function Cache_write ($filename, $values, $var = ' rows ', $format =false) {$cachefile = $filename; $cachetext = "<?php\r\n".
$ '. $var. ' = '. Arrayeval ($values, $format). ";";
Return WriteFile ($cachefile, $cachetext);
}//array converts to String function Arrayeval ($array, $format =false, $level =0) {$space = $line = ';
if (! $format) {for ($i =0; $i <= $level; $i + +) {$space. = "T";
} $line = "\ n"; $evaluate = ' Array '. $line. $space. '
('. $line;
$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, $format, $level + 1);
}else{ $evaluate. = $comma. $key. '
=> '. $val;
$comma = ', '. $line $space;
$evaluate. = $line. $space. ') ';
return $evaluate; //write File function WriteFile ($filename, $writetext, $openmod = ' W ') {if (false!== $fp =fopen ($filename, $openmod)) {Flo
CK ($FP, 2);
Fwrite ($fp, $writetext);
Fclose ($FP);
return true;
}else{return false;
}
}
(3) store the array in a text file directly by using Var_export
<?php
$file = './cache/phone.php ';
$array =array (' Color ' => array (' Blue ', ' red ', ' green '), ' size ' => array (' small ', ' medium ', ' large '));
Cache
$text = ' <?php $rows = '. Var_export ($array, true).
if (False!==fopen ($file, ' w+ ')) {
file_put_contents ($file, $text);
} else{
echo ' Create failure ';
The above is for you to introduce three kinds of PHP to save the array as a text format method, I hope to help you learn.