SplFileInfo:文件元資訊查詢(只讀)SplFileObject 繼承 SplFileInfo + 實現 RecursiveIterator、SeekableIterator:文件讀寫、遍歷、定位$f = new SplFileInfo('foo-bar.txt');
$info = [
'atime' => $f->getATime(), // 最後訪問時間
'ctime' => $f->getCTime(), // inode 變更時間
'mtime' => $f->getMTime(), // 內容修改時間
'size' => $f->getSize(), // 位元組大小
'type' => $f->getType(), // file/dir/link
'perm' => $f->getPerms(), // 權限掩碼
'owner' => $f->getOwner(), // UID
'group' => $f->getGroup(), // GID
'inode' => $f->getInode(), // inode 號
'realpath' => $f->getRealPath(), // 絕對路徑(解析鏈接)
'path' => $f->getPath(), // 目錄路徑
'filename' => $f->getFilename(), // 文件名
'basename' => $f->getBasename(), // 可帶後綴過濾
'extension' => $f->getExtension(), // 副檔名
'isFile' => $f->isFile(),
'isDir' => $f->isDir(),
'isLink' => $f->isLink(),
'isReadable' => $f->isReadable(),
'isWritable' => $f->isWritable(),
'isExecutable' => $f->isExecutable(),
];
print_r($info);
try {
foreach (new SplFileObject('large.log') as $lineNum => $line) {
// $line 含換行符,可用 rtrim($line)
if (strpos($line, 'ERROR') !== false) {
echo "Line $lineNum: $line";
}
}
} catch (RuntimeException $e) {
echo "Error: " . $e->getMessage();
}
$file = new SplFileObject('data.txt');
$file->seek(100); // 跳至第 101 行(0 基)
echo $file->current(); // 讀取該行
echo $file->key(); // 當前行號
// 寫入 CSV
$data = [
['id','name','email'],
[1,'Alice','alice@example.com'],
[2,'Bob','bob@example.com'],
];
$csv = new SplFileObject('users.csv', 'w');
foreach ($data as $row) {
$csv->fputcsv($row);
}
// 讀取 CSV
$csv = new SplFileObject('users.csv', 'r');
$csv->setFlags(SplFileObject::READ_CSV);
foreach ($csv as $row) {
print_r($row); // 已解析為陣列
}
| 常量 | 效果 |
|---|---|
READ_AHEAD | 預讀下一行(預設開啟) |
SKIP_EMPTY | 跳過空行 |
DROP_NEW_LINE | 移除行尾換行符 |
READ_CSV | 啟用 CSV 解析模式 |
組合使用:$f->setFlags(SplFileObject::READ_CSV | SplFileObject::SKIP_EMPTY | SplFileObject::DROP_NEW_LINE);
| 傳統函數 | SPL 類優勢 |
|---|---|
fopen/fgets/feof | OO 介面、自動資源管理、異常處理 |
fseek/ftell | SeekableIterator 標準協議 |
fgetcsv | 內建 CSV 旗標、自動處理引號/轉義 |
stat/pathinfo | 屬性方法化、鏈式調用、類型安全 |
| 手寫遞歸遍歷 | RecursiveIterator + RecursiveDirectoryIterator |
$dir = new RecursiveDirectoryIterator('/var/www');
$iter = new RecursiveIteratorIterator($dir, RecursiveIteratorIterator::SELF_FIRST);
foreach ($iter as $path => $info) {
if ($info->isFile() && $info->getExtension() === 'php') {
echo $info->getRealPath() . " ({$info->getSize()} bytes)\n";
}
}
SplFileInfo + SplFileObject 將文件系統操作提升為一等公民,是現代 PHP 專案處理文件的標準方式。