如何读取一个包含php中适当数组的文本文件


How can i read a text file which contains a proper array in php?

我用它将数组写入文本文件:

$fp = fopen('file.txt', 'w');
fwrite($fp, print_r($newStrings, TRUE));
fclose($fp);

现在我想在php中读回它,就像读普通数组一样?我该怎么做?我对这件事还很陌生,目前我正处于修复相关问题的最后期限,请帮忙。

var_export()将是有效的PHP代码,您可以使用include,并且比print_r()工作得更好,但我建议使用JSON/json_encode()serialize()的工作原理也类似于JSON,但不可移植。

写入:

file_put_contents('file.txt', json_encode($newStrings));

阅读:

$newStrings = json_decode(file_get_contents('file.txt'), true);

使用PHP序列化和取消序列化来完成此操作。

写入文件:

$myArray = ['test','test2','test3'];
$fp = fopen('file.txt', 'w');
fwrite($fp, serialize($myArray));
fclose($fp);

或者更苗条:

file_put_contents('file.txt',serialize($myArray));

再读一遍:

$myArray = unserialize(file_get_contents('file.txt'));

在写入数据时对其使用json_encode()或serialize(),然后在读取数据时对数据使用json_decode()或unserialize(

要查看差异,请检查此问题:JSON与数据库中的序列化数组