php 緩存數組形式的變量,實際上就是將 php 將數組寫入到一個文本文件或者后綴名為 .php 存儲起來,使用的時候直接調用這個文件。那么如何使用 php 將數組保存為文本格式的文件呢?下面分享三種方法實現將 php 數組寫入到文件以緩存數組。
(1)利用serialize 將數組序列化存儲為文本文件,調用時候再使用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)));
新聞熱點
疑難解答