简体   繁体   English

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

[英]How do I add content in a new row to a txt file

I would like to create a < input> where if someone enters text, a text file will add the content entered as a new row. 我想创建一个<input>,如果有人输入文本,文本文件将添加输入的内容作为新行。 I have tried highly modified the feature in this link: here 我已尝试高度修改此链接中的功能: 此处

Just use the PHP_EOL (PHP end of line) constant that will create a new line. 只需使用PHP_EOL (PHP行尾)常量即可创建新行。
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. a+表示文件已打开并存储在$file ,并且可以读取和写入。 The a stands for append; a代表追加; meaning the fwrite will append the file. 表示fwrite将附加文件。
See more on the PHP documentation . 有关更多信息请参见PHP文档

$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 . 由于您正在使用URL发送数据(建议不正确,但这完全是另一回事),因此可以通过超全局变量$_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. 这是因为$_GET是一个数组,如果要插值数组必须将它们包装,则类属性也是如此。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM