如何读取包含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()
要查看差异,请检查此问题: