Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/297.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 如何将内容放在.txt文件的第二行并读取它_Php_File Get Contents_File Put Contents - Fatal编程技术网

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

Php 如何将内容放在.txt文件的第二行并读取它,php,file-get-contents,file-put-contents,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 第二行怎么

为了在
.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

第二行怎么读呢?

除了应该使用MySQL这样的数据库之外,还可以使用这个函数。例如:

$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);

阅读第二行:

$myFile = "data/vote_result.txt";
$linesArray = file($myFile);
echo $linesArray[1]; //line 2
如果要在文件中追加一行,请在文件内容中使用file\u append标志,并将“\n”与内爆连接起来

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

你真的应该为此使用一个数据库