文件与目录操作
这篇讲 PHP 中常见的文件与目录操作:读写文件、检查文件状态、遍历目录,以及处理 CSV 等常见格式。文件操作是日志、上传、数据导入等功能的底层基础。
读取文件
读取整个文件内容
最简单的方式是用 file_get_contents() 将文件读入字符串:
<?php
$content = file_get_contents('data.txt');
echo $content;
?>
逐行读取
处理大文件时逐行读取更省内存:
<?php
$handle = fopen('data.txt', 'r');
while (($line = fgets($handle)) !== false) {
echo $line;
}
fclose($handle);
?>
处理大文件(如日志、CSV 数据)时,逐行读取远比
file_get_contents() 省内存——后者会把整个文件加载到内存中。写入文件
file_put_contents() 是最便捷的写入方式:
<?php
// 写入(覆盖模式)
file_put_contents('output.txt', "Hello PHP!\n");
// 追加模式
file_put_contents('output.txt', "第二行内容\n", FILE_APPEND);
?>
使用 fopen() + fwrite() 可以更精细地控制写入:
<?php
$handle = fopen('log.txt', 'a'); // 'a' = 追加模式
fwrite($handle, date('Y-m-d H:i:s') . " - 日志记录\n");
fclose($handle);
?>
文件打开模式
| 模式 | 说明 |
|---|---|
'r' | 只读,指针在文件开头 |
'w' | 只写,清空已有内容,文件不存在则创建 |
'a' | 追加写入,指针在文件末尾,不存在则创建 |
'r+' | 读写,指针在文件开头 |
'w+' | 读写,清空已有内容 |
检查文件与目录
PHP 提供了一系列函数来检查文件状态:
<?php
$path = 'data.txt';
file_exists($path); // 文件或目录是否存在
is_file($path); // 是否是文件
is_dir($path); // 是否是目录
is_readable($path); // 是否可读
is_writable($path); // 是否可写
filesize($path); // 文件大小(字节)
filemtime($path); // 最后修改时间(Unix 时间戳)
?>
目录操作
读取目录内容
使用 scandir() 获取目录中的文件和子目录列表:
<?php
$files = scandir('/path/to/directory');
foreach ($files as $file) {
if ($file === '.' || $file === '..') {
continue;
}
echo $file . "\n";
}
?>
创建和删除目录
<?php
// 创建目录(第三个参数 true 表示递归创建)
mkdir('/path/to/new/dir', 0755, true);
// 删除空目录
rmdir('/path/to/empty/dir');
?>
递归遍历目录
使用 RecursiveDirectoryIterator 递归遍历子目录中的所有文件:
<?php
$iterator = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator('/path/to/dir')
);
foreach ($iterator as $file) {
if ($file->isFile()) {
echo $file->getPathname() . "\n";
}
}
?>
CSV 文件处理
PHP 内置了方便的 CSV 读写函数:
<?php
// 读取 CSV
$handle = fopen('data.csv', 'r');
while (($row = fgetcsv($handle)) !== false) {
// $row 是一个数组,每个元素是一列的值
echo $row[0] . ' | ' . $row[1] . "\n";
}
fclose($handle);
// 写入 CSV
$data = [
['Name', 'Age', 'City'],
['Alice', '25', 'Beijing'],
['Bob', '30', 'Shanghai'],
];
$handle = fopen('output.csv', 'w');
foreach ($data as $row) {
fputcsv($handle, $row);
}
fclose($handle);
?>
操作完文件后记得用
fclose() 关闭句柄——虽然在脚本结束时 PHP 会自动关闭,但及时关闭可以释放资源,避免长时间运行的脚本耗尽文件句柄。一句话小结
读文件首选 file_get_contents()(小文件)或 fgets() 逐行(大文件),写文件用 file_put_contents() 或 fopen('a') 追加。目录操作用 scandir() 或递归迭代器。CSV 用 fgetcsv() / fputcsv()。操作前先检查文件状态,操作后及时关闭句柄。下一篇讲 错误与异常处理。
最后更新于