Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/242.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何读取包含php中正确数组的文本文件?_Php_Arrays_Robots.txt - Fatal编程技术网

如何读取包含php中正确数组的文本文件?

如何读取包含php中正确数组的文本文件?,php,arrays,robots.txt,Php,Arrays,Robots.txt,我使用它将数组写入文本文件: $fp = fopen('file.txt', 'w'); fwrite($fp, print_r($newStrings, TRUE)); fclose($fp); 现在我想用php读回它,就像我读回普通数组一样?我该怎么做?我是一个相当新的这个,我目前在一个期限内得到一些相关的这个固定,请帮助 使用PHP并执行此操作 写入文件: $myArray = ['test','test2','test3']; $fp = fopen('file.txt', 'w');

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

$fp = fopen('file.txt', 'w');
fwrite($fp, print_r($newStrings, TRUE));
fclose($fp);
现在我想用php读回它,就像我读回普通数组一样?我该怎么做?我是一个相当新的这个,我目前在一个期限内得到一些相关的这个固定,请帮助

使用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'));
将是有效的PHP代码,您可以
包括
,并且比
print\r()
工作得更好,但我建议使用JSON/。也可以类似于JSON,但不可移植

写入:

file_put_contents('file.txt', json_encode($newStrings));
$newStrings = json_decode(file_get_contents('file.txt'), true);
阅读:

file_put_contents('file.txt', json_encode($newStrings));
$newStrings = json_decode(file_get_contents('file.txt'), true);
在写入数据时对其使用json_encode()或serialize(),然后在读取数据时对其使用json_decode()或unserialize()

要查看差异,请检查此问题: