-1

I have 2 php files, first.php and second.php. The job of both the PHP files are to write a string value to a text file called "newfile.txt".

ISSUE im facing: With the method shown below the second.php will overwrite whatever the first.php has written in the text file.

GOAL: I want to write the value outputted by first.php in the first line and value of second.Php in the second line of the same text file(ie newfile.txt ). So whatever First.php outputs, i would like to update the first line and whatever second.php outputs i would like to update it in the second line.

IMPORTANT NOTE: I dont want to create a new line. I want to update the line first.php

$myfile = fopen("newfile.txt", "w") or die("Unable to open file!");
$txt = "LIGHTS TURNED ON";
fwrite($myfile, $txt);
fclose($myfile);

second.php

$myfile = fopen("newfile.txt", "w") or die("Unable to open file!");
$txt = "LIGHTS TURNED OFF";
fwrite($myfile, $txt);
fclose($myfile);

Example of how intend newfile.txt to be

LIGHTS TURNED ON      //update whatever first.php outputs
LIGHTS TURNED OFF    //update whatever second.php outputs

Thank you so much for reading.

JTC
  • 119
  • 1
  • 11
  • you just need to change the file opening mode: you open it in write mode, which means that all the content of the file is deleted and truncate the file to zero length. Try to change it to append mode: `$myfile = fopen("newfile.txt", "a") or die("Unable to open file!");` – Zeusarm Feb 19 '21 at 04:55
  • @AlivetoDie those method are not for updating the line, they just create a new line. i want to update Line 1 and 2 – JTC Feb 19 '21 at 05:05
  • Hey @Zeusarm Thanks for replying, putting append creates a new line which i dont want. I want the update the exsiting Line – JTC Feb 19 '21 at 05:05
  • @AlivetoDie if you have closed this question, please undo it, as i need an answer – JTC Feb 19 '21 at 05:27
  • https://stackoverflow.com/questions/3004041/how-to-replace-a-particular-line-in-a-text-file-using-php – Alive to die - Anant Feb 19 '21 at 05:32
  • Hey @esqew Thanks for repling. I dont have a particular word to change, i just need to change the entire row. The words can change constantly. So i need to update whatever the word is – JTC Feb 19 '21 at 05:36

1 Answers1

0

A simple (yet memory inefficient) way of accomplishing this would be to first read the file into an array by line (file()), updating based on the line index, then writing the file back as you've already got with fwrite():

$file_contents_array = file("newfile.txt");

$file_contents_array[0] = "THIS IS LINE ONE, BUT CHANGED";
$file_contents_array[1] = "THIS IS LINE TWO, BUT CHANGED";

$myfile = fopen("newfile.txt", "w") or die("Unable to open file!");
fwrite($myfile, implode("\n", $file_contents_array));
fclose($myfile);

Repl.it

esqew
  • 42,425
  • 27
  • 92
  • 132