php实现文件读写操作
PHP 文件读取操作
使用 file_get_contents() 函数可以快速读取文件内容,适合读取小型文件。该函数将整个文件内容读取为一个字符串。
$content = file_get_contents('example.txt');
echo $content;
对于逐行读取大型文件,可以使用 fopen() 和 fgets() 组合。这种方式内存占用较低,适合处理大文件。
$handle = fopen('example.txt', 'r');
if ($handle) {
while (($line = fgets($handle)) !== false) {
echo $line;
}
fclose($handle);
}
PHP 文件写入操作
使用 file_put_contents() 函数可以快速写入内容到文件。如果文件不存在会自动创建,默认会覆盖原有内容。
$data = "Hello, World!";
file_put_contents('example.txt', $data);
需要追加内容而不是覆盖时,可以添加 FILE_APPEND 标志。
$data = "New line of text";
file_put_contents('example.txt', $data, FILE_APPEND);
对于更复杂的写入操作,可以使用 fopen() 配合 fwrite()。这种方式允许更灵活的控制。
$handle = fopen('example.txt', 'w');
if ($handle) {
fwrite($handle, "First line\n");
fwrite($handle, "Second line\n");
fclose($handle);
}
检查文件是否存在
在操作文件前最好检查文件是否存在,避免错误。

if (file_exists('example.txt')) {
echo "文件存在";
} else {
echo "文件不存在";
}
文件权限处理
确保脚本有足够的权限读写文件。可以通过 chmod() 修改文件权限。
chmod('example.txt', 0644);
错误处理
文件操作时应该加入错误处理机制,使用 try-catch 块捕获可能的异常。
try {
$content = file_get_contents('nonexistent.txt');
if ($content === false) {
throw new Exception('文件读取失败');
}
echo $content;
} catch (Exception $e) {
echo '错误: ' . $e->getMessage();
}
CSV 文件处理
对于 CSV 格式的文件,可以使用专门的函数 fgetcsv() 和 fputcsv() 进行处理。

读取 CSV 文件:
$handle = fopen('data.csv', 'r');
if ($handle) {
while (($data = fgetcsv($handle)) !== false) {
print_r($data);
}
fclose($handle);
}
写入 CSV 文件:
$list = [
['Name', 'Email', 'Phone'],
['John', 'john@example.com', '123456'],
['Jane', 'jane@example.com', '789012']
];
$handle = fopen('output.csv', 'w');
if ($handle) {
foreach ($list as $row) {
fputcsv($handle, $row);
}
fclose($handle);
}
文件锁定机制
在多进程/多线程环境下操作文件时,应该使用文件锁定避免冲突。
$handle = fopen('example.txt', 'a');
if (flock($handle, LOCK_EX)) {
fwrite($handle, "Locked content\n");
flock($handle, LOCK_UN);
}
fclose($handle);
临时文件处理
需要创建临时文件时,可以使用 tmpfile() 函数,该文件会在脚本结束时自动删除。
$temp = tmpfile();
fwrite($temp, "Temporary data");
fclose($temp); // 文件自动删除






