如何将新行中的内容添加到txt文件中

如何将新行中的内容添加到txt文件中

问题描述:

I would like to create a < input> where if someone enters text, a text file will add the content entered as a new row. I have tried highly modified the feature in this link: here

我想创建一个&lt; 输入&GT; 如果有人输入文本,文本文件将添加作为新行输入的内容。 我尝试过对此链接中的功能进行了大幅修改:此处 div>

Just use the PHP_EOL (PHP end of line) constant that will create a new line.
This must be appended at the end of each line.

$file = fopen("myfile.txt", "a+");
fwrite($file, "hello".PHP_EOL);
// or...
fwrite($file, $myvar.PHP_EOL);

Alternatively, you could create your own, new, function:

function fwrite2($handle, string $string, $length = null, $newline = true) {
    $string = $newline ? $string.PHP_EOL : $string;

    if (isset($length)) {
        fwrite($handle, $string, $length);
    } else {
        fwrite($handle, $string);
    }
}

Call the above in the same manner, except the third argument will now create a new line automatically.


Edit following the comments:

The a+ means that the file is open and stored in $file and is available for reading and writing. The a stands for append; meaning the fwrite will append the file.
See more on the PHP documentation.

$file = fopen("myfile.txt", "a+");
fwrite2($file, "{$_GET['message']} | from {$_GET['sender']}");

Since you are using the URL to send data (ill-advised, but that is another point completely), you can access its contents through the superglobal variable - $_GET.
Notice that I have wrapped the values in curly braces. This is because $_GET is an array and if you want to interpolate arrays they must be wrapped, the same goes for class properties.