欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

php將數(shù)組存儲(chǔ)為文本文件方法匯總

 更新時(shí)間:2015年10月28日 15:23:29   投稿:lijiao  
這篇文章主要介紹了php將數(shù)組存儲(chǔ)為文本文件的三種方法,每個(gè)方法都有利弊,需要的朋友可以參考下

php 緩存數(shù)組形式的變量,實(shí)際上就是將 php 將數(shù)組寫(xiě)入到一個(gè)文本文件或者后綴名為 .php 存儲(chǔ)起來(lái),使用的時(shí)候直接調(diào)用這個(gè)文件。那么如何使用 php 將數(shù)組保存為文本格式的文件呢?下面分享三種方法實(shí)現(xiàn)將 php 數(shù)組寫(xiě)入到文件以緩存數(shù)組。
(1)利用serialize 將數(shù)組序列化存儲(chǔ)為文本文件,調(diào)用時(shí)候再使用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));//寫(xiě)入緩存 
} 
//讀出緩存 
$handle=fopen($file,'r'); 
$cacheArray=unserialize(fread($handle,filesize($file))); 

(2)自創(chuàng)的將數(shù)組保存為標(biāo)準(zhǔn)的數(shù)組格式,雖然保存時(shí)復(fù)雜了點(diǎn)但是調(diào)用時(shí)簡(jiǎn)單

<?php 
$file='./cache/phone.php'; 
$array=array('color'=> array('blue','red','green'),'size'=> array('small','medium','large')); 
cache_write($file,$array,'rows',false); 
 
//寫(xiě)入 
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; 
} 
 
//寫(xiě)入文件 
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ù)組形式存儲(chǔ)到文本文件中

<?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ù)組保存為文本格式的方法,希望對(duì)大家的學(xué)習(xí)有所幫助。

相關(guān)文章

最新評(píng)論