This question already has an answer here:
I have a very specific case. I have a text document that stores text as such: ["TEXT1","TEXT2","TEXT3"] I would like to create a form where a user inputs in text, and it automatically gets added into this file. The file is backend however. If there is a way to do this without backend, that would be sufficient, however if possible, I would like to know aswell.
Thanks
</div>
First open file with readwrite
mode. Then get the content from file. Your text file having content ["TEXT1","TEXT2","TEXT3"]. To add user input at end of this text, you have to remove last "]"
from text. so use rtrim()
function for removing that & then you can append the user input at end. Finally you can write that code to text document file with fwrite()
.
$my_file = 'randumb.txt';
$handle = fopen($my_file,'r+');
$array = file_get_contents($my_file);
$input = "TEXT4";
$output = rtrim($array, "]"). ",\"" .$input ."\"". ']';
fwrite($handle, $output);
Output In text document file:
["TEXT1","TEXT2","TEXT3","TEXT4"]