fwrite() 函数是 PHP 中用于将数据写入文件的函数
fopen() 函数打开要写入的文件。如果文件不存在,fopen() 将创建一个新文件;如果文件已存在,fopen() 将打开该文件以便进行写入。$file = fopen("example.txt", "w"); // "w" 表示以写入模式打开文件,如果文件不存在则创建新文件,如果文件已存在则清空内容检查文件是否成功打开:使用 is_resource() 函数检查 $file 是否为一个有效的文件资源。if (!is_resource($file)) { die("Error: Unable to open file.");}写入数据:使用 fwrite() 函数将数据写入文件。fwrite() 函数接受两个参数:第一个参数是文件资源,第二个参数是要写入的数据。$data = "Hello, World!";$result = fwrite($file, $data);fwrite() 函数返回写入的字节数。您可以检查 $result 以确保已成功写入数据。
fclose() 函数关闭已打开的文件。fclose($file);将以上步骤组合在一起,完整的示例代码如下:
<?php$file = fopen("example.txt", "w");if (!is_resource($file)) { die("Error: Unable to open file.");}$data = "Hello, World!";$result = fwrite($file, $data);if ($result === false) { echo "Error: Failed to write data to file.";} else { echo "Data written to file successfully. Written bytes: " . $result;}fclose($file);?>注意:使用 w 模式打开文件会清空文件内容,如果需要在文件末尾追加内容,请使用 a 或 a+ 模式打开文件。