php - 读取保存在文件中的 php 数组?

标签 php file-io

我在 .log 文件中保存了一些 php 数组

我想将它们读入一个 php 数组,例如

array[0] = .log 文件中的第一个数组 数组 1 = .log 文件中的第二个数组

解决方案 here对我不起作用

它没有给出这样的文件或目录错误,但是当我执行 include_once('file.log') 时,文件中的内容显示为输出(我不知道为什么)请帮忙

最佳答案

您可以在将数组作为文本写入文件之前序列化。然后,您可以从文件中读回数据,unserialize 会将其转回数组。

http://php.net/manual/en/function.serialize.php

EDIT 描述使用serialize/unserialize的过程:

所以你有一个数组:

$arr = array(
  'one'=>array(
      'subdata1',
      'subdata2'
  ),
  'two'='12345'
);

当我对该数组调用 serialize 时,我得到一个字符串:

$string = serialize($arr);
echo $string;

OUTPUT: a:2:{s:3:"one";a:2:{i:0;s:8:"subdata1";i:1;s:8:"subdata2";}s:3:"two";s:5:"12345";}

所以我想将该数据写入文件:

$fn= "serialtest.txt";
$fh = fopen($fn, 'w');
fwrite($fh, $string);
fclose($fh);

以后想用那个数组。所以,我将读取文件,然后反序列化:

$str = file_get_contents('serialtest.txt');
$arr = unserialize($str);
print_r($arr);

OUTPUT: Array ( [one] => Array ( [0] => subdata1 [1] => subdata2 ) [two] => 12345 ) 

希望对您有所帮助!

EDIT 2 嵌套演示

要随着时间的推移将更多数组存储到此文件中,您必须创建一个父数组。这个数组是所有数据的容器,所以当你想添加另一个数组时,你必须解包父数组,并将新数据添加到其中,然后重新打包整个数组。

首先,设置您的容器:

// Do this the first time, just to create the parent container
$parent = array();
$string = serialize($arr);
$fn= "logdata.log";
$fh = fopen($fn, 'w');
fwrite($fh, $string);
fclose($fh);

现在,从那里开始,当你想添加一个新数组时,首先你必须取出整个包并反序列化它:

// get out the parent container
$parent = unserialize(file_get_contents('logdata.log'));

// now add your new data
$parent[] = array(
  'this'=>'is',
  'a'=>'new',
  'array'=>'for',
  'the'=>'log'
);

// now pack it up again
$fh = fopen('logdata.log', 'w');
fwrite($fh, serialize($parent));
fclose($fh);

关于php - 读取保存在文件中的 php 数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4997186/

相关文章:

php - Google Weather API 温度转换

wpf - 使用WPF Imaging类-在不读取整个文件的情况下获取图像尺寸

php - WooCommerce 电子邮件样式 - 删除默认样式

php - 如何确保比较区分大小写?

php - Cakephp 数据表 SSP 分组依据

windows - 跟踪对 Delphi 中的文件夹所做的更改

java - 如何在初始化时在类的构造函数调用中容纳一个 FileInputStream 对象为 InputStream 对象?

java - 如何获取文件目录的绝对路径?

android - 将位图保存到文件功能

php - 如何使用 MySQL MATCH AGAINST IN BOOLEAN MODE 返回关键字字符串中至少 1 个匹配关键字的结果?