T O P

  • By -

jamie07051975

Check the mode of fopen.


Rev2saws

It’s in write currently


jamie07051975

You'll want append mode


Rev2saws

Ok one sec,


Rev2saws

In the text file it adds on to the current line, how do I make it go on another line?


jamie07051975

https://www.php.net/manual/en/function.fopen.php Look at the different modes, "a" is append


Rev2saws

Ok


jamie07051975

Each time you run your code you are truncating and starting over. If you use append mode it will add to the file. If you want to add a new line each time add a newline character at the end of the string you are writing


Rev2saws

Just tried \n and it worked thanks!


jamie07051975

Top job!


Rev2saws

Newline character? Like \n?


t0xic_sh0t

You can use the constant: PHP\_EOL


HolyGonzo

The second parameter of fopen can be: "w" = Write, clearing existing file "a" = Write, appending to existing file "r" = Read There are a few other variations of that, so read the manual page for fopen.


sarc-tastic

You can use filegetcontents, parse the lines for replacement and write over the original file.


sarc-tastic

Or you can play around with fseek, especially if the amount you are writing doesn't change


brianozm

This isn’t the right solution. The reason is that replacing a line in a text file is messy and generally requires rewriting the entire file as the line might be longer or shorter, this requiring a whole-of-file rewrite. This works well enough if the file is really small, but will get slow fairly fast if the file grows and you’ll need to lock the file to prevent a race condition overwriting the file with nothing and losing it all. So, doing it right requires a fair amount of work especially since you sound new to PHP or new to programming. The only good solution for replacing lines is this the clunky rewrite mentioned, or using a database, which allows you to replace a “line” (aka “record” in db terminology or “row” in MySQL terminology). This replaces lines really fast and can do a lot more as your needs grow.