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

狂风中的少年 提交于 2021-02-16 18:17:06

问题


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


回答1:


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



回答2:


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.




回答3:


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



来源:https://stackoverflow.com/questions/38841280/writing-a-new-and-appending-a-file-in-php-without-erasing-contents

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!