php 緩衝數組形式的變數,實際上就是將 php 將數組寫入到一個文字檔或者尾碼名為 .php 儲存起來,使用的時候直接調用這個檔案。
那麼如何使用 php 將數組儲存為文字格式設定的檔案呢?
下面分享三種方法實現將 php 數組寫入到檔案以緩衝數組。
(1)利用 serialize 將數組序列化儲存為文字檔,調用時候再使用 unserialize 還原
$file='./cache/phone.php';
$array=array('color'=> array('blue','red','green'),'size'=> array('small','medium','large'));
//緩衝
if(false!==fopen($file,'w+')){
file_put_contents($file,serialize($array));//寫入緩衝
}
//讀出緩衝
$handle=fopen($file,'r');
$cacheArray=unserialize(fread($handle,filesize($file)));
(2)自創的將數組儲存為標準的數組格式,雖然儲存時複雜了點但是調用時簡單
$file='./cache/phone.php';
$array=array('color'=> array('blue','red','green'),'size'=> array('small','medium','large'));
cache_write($file,$array,'rows',false);
//寫入
function cache_write($filename,$values,$var='rows',$format=false){
$cachefile=$filename;
$cachetext="return writefile($cachefile,$cachetext);
}
//數群組轉換成字串
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;
}
//寫入檔案
function writefile($filename,$writetext,$openmod='w'){
if(false!==$fp=fopen($filename,$openmod)){
flock($fp,2);
fwrite($fp,$writetext);
fclose($fp);
return true;
}else{
return false;
}
}
(3)利用 var_export 將數組直接儲存為數組形式儲存到文字檔中
$file='./cache/phone.php';
$array=array('color'=> array('blue','red','green'),'size'=> array('small','medium','large'));
//緩衝
$text='if(false!==fopen($file,'w+')){
file_put_contents($file,$text);
}else{
echo '建立失敗';
}