用PHP编写新文件并附加文件而不删除内容 [英] Writing a new and appending a file in PHP without erasing contents

查看:66
本文介绍了用PHP编写新文件并附加文件而不删除内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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);
    };

?>

这是文件的外观当前视图

这应该是理想视图

推荐答案

简单地:

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)

如果新行不起作用,则问题出在您的 $ newLine 变量,而不是文件追加操作.以下之一将起作用:

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

这篇关于用PHP编写新文件并附加文件而不删除内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆