简体   繁体   中英

How do I put content on second line in .txt file and read it

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?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM