php將數(shù)組存儲為文本文件方法匯總
php 緩存數(shù)組形式的變量,實際上就是將 php 將數(shù)組寫入到一個文本文件或者后綴名為 .php 存儲起來,使用的時候直接調(diào)用這個文件。那么如何使用 php 將數(shù)組保存為文本格式的文件呢?下面分享三種方法實現(xiàn)將 php 數(shù)組寫入到文件以緩存數(shù)組。
(1)利用serialize 將數(shù)組序列化存儲為文本文件,調(diào)用時候再使用unserialize 還原
<?php $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)自創(chuàng)的將數(shù)組保存為標準的數(shù)組格式,雖然保存時復(fù)雜了點但是調(diào)用時簡單
<?php $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="<?php\r\n".'$'.$var.'='.arrayeval($values,$format).";"; return writefile($cachefile,$cachetext); } //數(shù)組轉(zhuǎn)換成字串 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 將數(shù)組直接保存為數(shù)組形式存儲到文本文件中
<?php $file='./cache/phone.php'; $array=array('color'=> array('blue','red','green'),'size'=> array('small','medium','large')); //緩存 $text='<?php $rows='.var_export($array,true).';'; if(false!==fopen($file,'w+')){ file_put_contents($file,$text); }else{ echo '創(chuàng)建失敗'; }
以上就是為大家介紹的三種php將數(shù)組保存為文本格式的方法,希望對大家的學習有所幫助。
相關(guān)文章
php curl獲取https頁面內(nèi)容,不直接輸出返回結(jié)果的設(shè)置方法
今天小編就為大家分享一篇php curl獲取https頁面內(nèi)容,不直接輸出返回結(jié)果的設(shè)置方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-01-01PHP實現(xiàn)JS中escape與unescape的方法
這篇文章主要介紹了PHP實現(xiàn)JS中escape與unescape的方法,通過json_encode和json_decode方法實現(xiàn)JS中escape與unescape函數(shù)的功能,需要的朋友可以參考下2016-07-07PHP MySQL應(yīng)用中使用XOR運算加密算法分享
本文將介紹一個簡單易用的加密/解密算法:使用異或(XOR)運算。本算法原理簡單,旨在使讀者對信息的加密/解密有一個更加直觀的印象。2011-08-08