4

How could one write a new line to a file in php without erasing all the other contents of the file?

<?php
if(isset($_POST['songName'])){

        $newLine = "\n";
        $songName = $_POST['songName'];
        $filename = fopen('song_name.txt', "wb");
        fwrite($filename, $songName.$newLine);
        fclose($filename);
    };

?>

This is what the file looks like Current view

This is what is should look like Ideal View

Giga Chad Coding
  • 178
  • 3
  • 12

3 Answers3

5

Simply:

file_put_contents($filename,$songName.$newLine,FILE_APPEND);

Takes care of opening, writing to, and closing the file. It will even create the file if needed! (see docs)

If your new lines aren't working, the issue is with your $newLine variable, not the file append operations. One of the following will work:

$newLine = PHP_EOL;  << or >>  $newLine = "\r\n";
BeetleJuice
  • 39,516
  • 19
  • 105
  • 165
  • This does not add a new line to the file, it merely appends on to the end of the current line – Giga Chad Coding Aug 09 '16 at 03:01
  • @JohnSmith All file append operations, including the other solution, do the same thing. it appends whatever you indicate. If you want a new line, start with a new line character :-). Eg: append `$newLine.$songName.$newLine` – BeetleJuice Aug 09 '16 at 03:04
  • @JohnSmith I think it would help if you showed what you're getting, and what you expect to get. Your last comment under the other answer seems to be different from the OP. Do you want to add just one line (as in the OP), or add a new line at the end of each existing line (as in your comment)? – BeetleJuice Aug 09 '16 at 03:10
  • I attached images of the desired results to be displayed by the file – Giga Chad Coding Aug 09 '16 at 03:16
  • That works now, thank you for your help, it is very much appreciated! I Marked yours as the answer! – Giga Chad Coding Aug 09 '16 at 03:20
  • @JohnSmith good to know. Suggest you upvote both answers because Robert had the right idea too, just a different approach to appending content. – BeetleJuice Aug 09 '16 at 03:22
4

You have it set for writing with the option w which erases the data.

You need to "append" the data like this:

$filename = fopen('song_name.txt', "a");

For a complete explanation of what all options do, read here.

Robert
  • 10,126
  • 19
  • 78
  • 130
2

To add a new line to a file and append it, do the following

$songName = $_POST['songName'];
        $filename = fopen('song_name.txt', "a+");
        fwrite($filename, $songName.PHP_EOL);
        fclose($filename);

PHP_EOL will add a new line to the file

Giga Chad Coding
  • 178
  • 3
  • 12