简体   繁体   中英

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. 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.
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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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