-6

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

1 Answers1

-1

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"]
Shivrudra
  • 674
  • 4
  • 5
  • `rtrim($array, "]"). ",\"" .$input ."\"". ']'`!? – Lawrence Cherone Jul 06 '18 at 06:26
  • Existing file having ["TEXT1","TEXT2","TEXT3"] & we need to add User input "Text4" in existing file. So output will be ["TEXT1","TEXT2","TEXT3","TEXT4"]. – Shivrudra Jul 06 '18 at 06:34
  • Because its a poor answer, why on earth would you use concatenation? What happens if the user enters a `"`? – Lawrence Cherone Jul 06 '18 at 06:37
  • If user input `"` then `"` will append to last of strings. Output will be Example: ["TEXT1","TEXT2","TEXT3","TEXT4"," " "]. In question he mentioned text document having word quoted with `"`. – Shivrudra Jul 06 '18 at 06:44
  • Sure, but then what happens when the OP wants to get the values in PHP? `explode('","', $array)`? Your answer creates an XY problem. – Lawrence Cherone Jul 06 '18 at 06:49