PHP SPL文件操作类概述
在PHP的标准库(SPL)中,系统内置了SplFileInfo和SplFileObject这两个关键类,专门用于简化复杂的文件处理任务。
SplFileInfo类的主要功能是提取文件的详细属性信息,而不涉及文件内容的读取或修改。
以下是使用代码获取文件属性的示例: $file = new SplFileInfo('foo-bar.txt'); print_r(array( 'getATime' => $file->getATime(), // 最后访问时间 'getBasename' => $file->getBasename(), // 不含路径的文件名部分 'getCTime' => $file->getCTime(), // inode修改时间 'getExtension' => $file->getExtension(), // 文件扩展名 'getFilename' => $file->getFilename(), // 完整文件名 'getGroup' => $file->getGroup(), // 所属组 'getInode' => $file->getInode(), // inode节点号 'getLinkTarget' => $file->getLinkTarget(), // 软链接指向的目标 'getMTime' => $file->getMTime(), // 最后修改时间 'getOwner' => $file->getOwner(), // 拥有者 'getPath' => $file->getPath(), // 不包含文件名的目录路径 'getPathInfo' => $file->getPathInfo(), // 父目录的SplFileInfo对象 'getPathname' => $file->getPathname(), // 绝对路径 'getPerms' => $file->getPerms(), // 权限模式 'getRealPath' => $file->getRealPath(), // 解析后的绝对路径 'getSize' => $file->getSize(), // 文件大小(字节) 'getType' => $file->getType(), // 类型:file, dir, link 'isDir' => $file->isDir(), // 是否为目录 'isFile' => $file->isFile(), // 是否为普通文件 'isLink' => $file->isLink(), // 是否为符号链接 'isExecutable' => $file->isExecutable(), // 是否可执行 'isReadable' => $file->isReadable(), // 是否可读 'isWritable' => $file->isWritable() // 是否可写 ));
SplFileObject类不仅继承了SplFileInfo的所有功能,还实现了RecursiveIterator和SeekableIterator接口,从而支持对文件内容进行遍历、定位查找及直接操作。
主要操作包括: 1. 遍历文件内容: try { foreach(new SplFileObject('foo-bar.txt') as $line) { echo $line; } } catch (Exception $e) { echo $e->getMessage(); } 2. 查找并读取指定行: try { $file = new SplFileObject('foo-bar.txt'); $file->seek(2); // 移动到第3行(索引从0开始) echo $file->current(); } catch (Exception $e) { echo $e->getMessage(); } 3. 写入CSV格式数据: $list = array ( array( 'aaa' , 'bbb' , 'ccc' , 'dddd' ), array( '123' , '456' , '7891' ), array( '"aaa"' , '"bbb"' ) ); $file = new SplFileObject ( 'file.csv' , 'w' ); foreach ( $list as $fields ) { $file -> fputcsv ( $fields ); }