如何将内容放在.txt文件的第二行并读取它

时间:2016-08-03 21:22:37

标签: php file-get-contents file-put-contents

为了在.txt文件中存储值,我使用以下代码:

file_put_contents('data/vote_result.txt', implode(',', $results));

用于阅读我用这个:

$results = explode(',', file_get_contents('data/vote_result.txt'));

vote_result.txt的内容如下所示:0,1,2,3

如何在同一个.txt文件中存储第二行,以便内容如下所示:

0,1,2,3
0,1,2,3

如何阅读第二行?

2 个答案:

答案 0 :(得分:0)

除此之外,你应该使用像MySQL这样的数据库,你可以使用file函数。例如:

$data = file('file.txt');
print $data[1]; // printing out the second line

这给出了你可以简单地通过在数组中添加一个新条目来添加新行,然后使用换行符将其内爆并通过file_put_contents函数保存它。

$content = implode("\n", $data);
file_put_contents('file.txt', $content);

答案 1 :(得分:0)

阅读第二行:

$myFile = "data/vote_result.txt";
$linesArray = file($myFile);
echo $linesArray[1]; //line 2

如果要在文件中添加一行,请在file_put_contents中使用 FILE_APPEND 标记并连接" \ n"内爆。

file_put_contents('data/vote_result.txt', implode(',', $results)."\n", FILE_APPEND);