php - 用 PHP 编写一个新文件并附加一个文件而不删除内容

标签 php fwrite

如何在不删除文件的所有其他内容的情况下在 php 中向文件中写入新行?

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

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

?>

这是文件的样子
Current view

这应该看起来像 Ideal View

最佳答案

简单地:

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

负责打开、写入和关闭文件。如果需要,它甚至会创建文件! ( see docs )

如果您的新行不起作用,则问题在于您的 $newLine 变量,而不是文件附加操作。以下方法之一将起作用:
$newLine = PHP_EOL;  << or >>  $newLine = "\r\n";

关于php - 用 PHP 编写一个新文件并附加一个文件而不删除内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38841280/

相关文章:

php - 根据特定列中存在的值对表进行排序

php - 在 Apache CouchDB 中按键搜索

php - 获取字段需要表名作为参数

c++ - 使用包含数组的结构进行 fwrite

c - 使用 fwrite 将由标记分隔的多个字符串打印到二进制文件中

php - Magento 服务器端表单验证

php - 与本地主机数据库的连接问题

file - 在 GWT 项目中写入文本文件?

c - 为什么我没有向 Roller2.raw 写入任何内容?

c++ - 使用 fwrite 转储的文件是否可以跨不同系统移植?