悠悠楠杉
PHP文件操作指南:从基础到进阶
1. 文件读取
1.1 使用fopen
和fread
php
$file = fopen("example.txt", "r"); // 打开文件以供读取
if ($file) {
$content = fread(fopen("example.txt", "r"), filesize("example.txt")); // 读取整个文件内容
echo $content;
fclose($file); // 关闭文件句柄
} else {
echo "无法打开文件";
}
1.2 使用fgets
逐行读取
php
$file = fopen("example.txt", "r");
if ($file) {
while (!feof($file)) { // 检测是否到达文件末尾
$line = fgets($file); // 读取一行内容
echo $line; // 输出该行内容
}
fclose($file); // 关闭文件句柄
} else {
echo "无法打开文件";
}
2. 文件写入和创建
2.1 使用fwrite
写入文件内容
php
$file = fopen("newfile.txt", "w"); // 打开文件以供写入,如果文件不存在则创建之
if ($file) {
fwrite($file, "这是一段新的文本内容。"); // 写入内容到文件
fclose($file); // 关闭文件句柄以保存更改
} else {
echo "无法打开/创建文件";
}
2.2 使用file_put_contents
写入内容(简单快捷)
php
$content = "使用file_put_contents直接写入内容。";
file_put_contents("newfile2.txt", $content); // 写入内容并自动创建文件(如果需要)
3. 文件删除和重命名
3.1 使用unlink
删除文件
php
unlink("example.txt"); // 删除文件(如果存在)
3.2 使用rename
重命名或移动文件/目录(可跨目录)
php
rename("oldname.txt", "newname.txt"); // 重命名/移动文件(如果目标位置存在同名文件,则被覆盖)
4. 目录操作与遍历
4.1 使用opendir
, readdir
, closedir
遍历目录(递归遍历示例)
php
function readDirRecursively($dir) {
$files = scandir($dir); // 获取目录下所有文件和子目录的数组,包括'.'和'..'等特殊项。通常需要排除它们。 for ($i = 0; $i < count($files); $i++) { // 遍历数组中的每一项(除'.'和'..'外) if (is_dir($dir . '/' . $files[$i])) { // 如果当前项是目录则递归调用自身 readDirRecursively($dir . '/' . $files[$i]); } else { echo $dir . '/' . $files[$i] . "\n"; // 输出文件名 // 处理每个文件 // ... } } closedir($dir); // 关闭目录句柄}readDirRecursively('path/to/directory'); // 从指定目录开始递归遍历打印所有文件名和子目录名。$dir可以替换为任意想要开始的目录路径。)