Home >php教程 >php手册 >PHP把数组写入文件实例代码

PHP把数组写入文件实例代码

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOriginal
2016-06-13 09:48:03931browse

在php中数组写入文件的方法有很多种,像我们要做成缓存文件就会把php数组转换成文件然后保存到.php文件,调用时直接调用此文件即可。

php把数组写入文件,通过序列和反序列实现。请看代码


$file="./data/file.cache";
file_put_contents($file,serialize($array));//写入缓存

 代码如下 复制代码

$file="./data/file.cache";
 
$array = array("count" => "3000",
 
               "num"  =>"300");
 
//缓存
 
file_put_contents($file,serialize($array));//写入缓存
?>


$file="./data/file.cache";
$handle = fopen($file, "r");
$cacheArray = unserialize(fread($handle, filesize ($file)));
print_r($cacheArray);
?>

//将一个测试的数组写入一个PHP文件:

 代码如下 复制代码

$write_array = array( '1' => 'oneone', '2' => 'two', '3' => 'three', '4' => 'four', '5' => 'five' ); //字符串处理
$string_start = ""; $string = $string_start.$string_process.$string_end; //开始写入文件
echo file_put_contents('test_array.php', $string);
?>

 
这里用到了两个函数:

 代码如下 复制代码

1,var_export():

·var_export — 用来输出或返回一个变量的字符串表示,它和 var_dump() 的区别是,var_export() 可以用来返回关于传递给该函数的变量的结构信息,并且其返回的表示是合法的 PHP 代码如果 “echo $string_process;”,则可以看到输出结果:

 代码如下 复制代码
array ( 1 => 'oneone', 2 => 'two', 3 => 'three', 4 => 'four', 5 => 'five', )

 
而它就是我们要写入 test_array.php 文件的内容(除去 php 标签);

·var_dump() 函数用来打印变量的相关信息,它只用来“打印”,而不会返回值,它的原型是 void var_dump(……),我们来 “var_dump($string_process);”,则可以看到输出结果:

 代码如下 复制代码
string(86) "array ( 1 => 'oneone', 2 => 'two', 3 => 'three', 4 => 'four', 5 => 'five', )"

 

可以看到输出的string(86) “…”,再一次说明了 var_export() 返回的是一个字符串。

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn