PHP 文件创建/写入

下面的例子创建名为 "testfile.txt" 的新文件。此文件将被创建于 PHP 代码所在的相同目录中:

$myfile = fopen("testfile.txt", "w")

下面的例子把姓名写入名为 "newfile.txt" 的新文件中:

<?php
$myfile = fopen("newfile.txt", "w") or die("Unable to open file!");
$txt = "Bill Gates
";
fwrite($myfile, $txt);
$txt = "Steve Jobs
";
fwrite($myfile, $txt);
fclose($myfile);
?>

打开 "newfile.txt" 文件,它应该是这样的:

Bill Gates
Steve Jobs

如果现在 "newfile.txt" 包含了一些数据,所有已存在的数据会被擦除并以一个新文件开始。

<?php
$myfile = fopen("newfile.txt", "w") or die("Unable to open file!");
$txt = "Mickey Mouse
";
fwrite($myfile, $txt);
$txt = "Minnie Mouse
";
fwrite($myfile, $txt);
fclose($myfile);
?>

如果现在我们打开这个 "newfile.txt" 文件,Bill 和 Steve 都已消失,只剩下我们刚写入的数据:

Mickey Mouse
Minnie Mouse

参考:

https://www.w3school.com.cn/php/php_file_create.asp

原文地址:https://www.cnblogs.com/sea-stream/p/11279981.html