John Smith John Smith - 8 months ago 30
PHP Question

Writing a new and appending a file in PHP without erasing contents

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


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


This is what the file looks like
Current view

This is what is should look like Ideal View




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";