2

For storing values in a .txt file I use this code:

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

and for reading i use this:

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

The content of vote_result.txt looks like this: 0,1,2,3

How can I store a second line in the same .txt file so that the content looks like this:

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

and how can I read that second line?

Vaibhav Bajaj
  • 1,934
  • 16
  • 29
Jack Maessen
  • 1,780
  • 4
  • 19
  • 51

2 Answers2

1

Read second line:

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

If you want to append a line to file, use FILE_APPEND flag in file_put_contents and concatenate "\n" with implode.

file_put_contents('data/vote_result.txt', implode(',', $results)."\n", FILE_APPEND);
Firepro
  • 111
  • 3
0

Besides that you should use a database like MySQL for this, you can use the file function. Example:

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

This given you can simply add new lines just by adding a new entry in the array and then implode it with the newline character and save it via the file_put_contents function.

$content = implode("\n", $data);
file_put_contents('file.txt', $content);
Manuel Mannhardt
  • 2,191
  • 1
  • 17
  • 23