Skip to content

PHP 文件创建/写入

本章介绍如何使用 PHP 在服务器上创建文件和向文件写入内容。

使用 file_put_contents() 简化文件写入

Section titled “使用 file_put_contents() 简化文件写入”

对于许多常见场景,例如创建新文件或用新内容覆盖现有文件,file_put_contents() 函数提供了一种简单有效的方法。对于基本任务,它通常比更底层的 fopen()、fwrite() 和 fclose() 组合更受欢迎。

这个函数在一个调用中处理文件的打开、写入和关闭。如果文件不存在,它会尝试创建它。如果文件存在,默认情况下会覆盖其内容。

示例:创建文件 ‘myfile.txt’ 并写入内容:

<?php
$file = 'myfile.txt';
// Content to write to the file
// 要写入文件的内容
$content = "This is the first line.\nThis is the second line.\n";
// Write the contents to the file, overwriting the file if it exists.
// The function returns the number of bytes written on success, or false on failure.
// 将内容写入文件,如果文件存在则覆盖。
// 函数成功时返回写入的字节数,失败时返回 false。
if (file_put_contents($file, $content) !== false) {
echo "File created and content written successfully.";
} else {
echo "Error writing to file. Check permissions.";
}
?>

要追加内容而不是覆盖,请使用 FILE_APPEND 标志:

<?php
$file = 'myfile.txt';
$new_content = "Appending this line.\n";
// Append content to the file
// 向文件追加内容
if (file_put_contents($file, $new_content, FILE_APPEND | LOCK_EX) !== false) {
echo "Content appended successfully.";
} else {
echo "Error appending to file. Check permissions.";
}
// LOCK_EX prevents others from writing to the file at the same time
// LOCK_EX 阻止其他进程同时写入文件
?>

高级文件处理:fopen()、fwrite()、fclose()

Section titled “高级文件处理:fopen()、fwrite()、fclose()”

要对文件操作进行更多控制,例如逐行读取、使用特定的文件模式或更有效地处理大型文件,可以使用传统的 fopen()、fwrite() 和 fclose() 函数。

fopen() 函数用于打开文件或 URL。如果在不存在的文件上使用写入模式('w'、'a' 等),PHP 将尝试创建该文件。

常用模式包括:

  • 'r' - 只读。从文件开头开始。
  • 'w' - 只写。打开文件并将文件截断为零长度,如果文件不存在则创建新文件。
  • 'a' - 追加。只写打开,将文件指针放在文件末尾。如果文件不存在则创建文件。
  • 'x' - 创建并只写打开。如果文件已存在则失败。
  • 添加 '+'(例如,'r+'、'w+')以允许同时读写。

示例:使用 fopen() 创建 ‘testfile.txt’:

<?php
$filename = "testfile.txt";
$mode = "w"; // Write mode: creates if not exists, truncates if exists
// 写入模式:如果不存在则创建,如果存在则截断
// fopen() returns a file pointer resource on success, or false on error.
// fopen() 成功时返回一个文件指针资源,失败时返回 false。
$handle = fopen($filename, $mode);
if ($handle === false) {
echo "Error: Unable to open or create file '{$filename}'. Check permissions.";
} else {
echo "File '{$filename}' opened/created successfully.";
// Remember to close the file handle when done
// 完成后记得关闭文件句柄
fclose($handle);
}
?>

fwrite() 函数将字符串内容写入已打开的文件指针。

第一个参数是文件指针资源(来自 fopen()),第二个参数是要写入的字符串。

示例:将姓名写入 ‘newfile.txt’:

<?php
$filename = "newfile.txt";
$handle = fopen($filename, "w"); // Open in write mode
// 以写入模式打开
if ($handle) {
$txt = "John Doe\n";
fwrite($handle, $txt);
$txt = "Jane Doe\n";
fwrite($handle, $txt);
fclose($handle); // Close the file
// 关闭文件
echo "Data written to '{$filename}'.";
} else {
echo "Error opening '{$filename}' for writing.";
}
?>

运行此代码后,‘newfile.txt’ 将包含:

John Doe
Jane Doe

以 'w' 模式(写入)打开文件将擦除所有现有内容。如果你想添加到文件末尾,请使用 'a' 模式(追加)。

示例:使用 'w' 模式覆盖 ‘newfile.txt’:

<?php
$filename = "newfile.txt";
$handle = fopen($filename, "w"); // 'w' mode truncates the file
// 'w' 模式截断文件
if ($handle) {
$txt = "Mickey Mouse\n";
fwrite($handle, $txt);
$txt = "Minnie Mouse\n";
fwrite($handle, $txt);
fclose($handle);
echo "File '{$filename}' overwritten.";
} else {
echo "Error opening '{$filename}' for writing.";
}
?>

现在 ‘newfile.txt’ 只包含:

Mickey Mouse
Minnie Mouse

如果在创建或写入文件时遇到错误,通常是由于文件系统权限问题。运行 PHP 的 Web 服务器进程(例如 Apache、Nginx)需要权限才能写入脚本尝试创建或修改文件的目录。请查阅您的服务器文档或咨询托管服务提供商了解权限管理详情。

有关文件系统功能的完整参考,请查阅官方 PHP 文档。