php将数组或对象写入到文件的三种方法

php将数组或对象原样写入或保存到文件有三种方法能够实现

第一种方法是使用serialize,php

第二种方法是使用print_r,nginx

第三种方法是使用var_export,数组

本文章向你们介绍这三种方法是如何将数组写入到文件的,须要的朋友能够参考一下。缓存

第一:serialize方法

使用 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))); 

第二:print_r方法

用print_r 将数组打印到txt文件中。php-fpm

<?php
$b = array (
    'm' => 'monkey', 
    'foo' => 'bar', 
    'x' => array ('x', 'y', 'z'));

$results = print_r($b, true); 
file_put_contents('filename.txt', print_r($b, true));
?>

第三:var_export方法

用var_export 直接将数组以完整数组的形式存储到文件中。spa

<?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 '建立失败'; 
}

 

将对象完整的存储并追加到文件末尾debug

$file = "notic_" . date("Ymd") . ".log";
$ct = date("Y-m-d H:i:s", time());

file_put_contents($file, var_export($object,true)."\r\n", FILE_APPEND);

 

ps: 正常状况下输出到网页的数组会有限制,调试

php var_dump函数对数组进行打印时,对多维数组中数组的层级越多越深层,子数组会不显示,只用省略号代替。这样一来不便于程序的调试code

php的var_dump函数是php模块中xdebug模块所支持的,因此接下来咱们须要配置这个xdebug便可。

修改 php.ini

;设置显示最大的子节点数
xdebug.var_display_max_children=128
;设置显示最大的字节数
xdebug.var_display_max_data=512
;设置显示最大得层级(深度)
xdebug.var_display_max_depth=15

 

而后重启 php 服务

systemctl reload php-fpm nginx
相关文章
相关标签/搜索