PHP SPL provides two classes of splfileinfo and Splfileobject to handle file operations.
Splfileinfo used to get file details:
Copy CodeThe code is as follows:
$file = new Splfileinfo (' Foo-bar.txt ');
Print_r (Array (
' Getatime ' = $file->getatime (),//Last accessed time
' Getbasename ' = $file->getbasename (),//Get path-free basename
' Getctime ' = $file->getctime (),//Get Inode modification time
' GetExtension ' = $file->getextension (),//File extension
' GetFileName ' = $file->getfilename (),//Get file name
' Getgroup ' = $file->getgroup (),//Get filegroup
' Getinode ' = $file->getinode (),//Get file Inode
' Getlinktarget ' = $file->getlinktarget (),//Get File link destination file
' Getmtime ' = $file->getmtime (),//Get Last Modified time
' GetOwner ' = $file->getowner (),//File owner
' GetPath ' = $file->getpath (),//file path without file name
' GetPathInfo ' = $file->getpathinfo (),//Splfileinfo object of the parent path
' GetPathName ' = $file->getpathname (),//full path
' Getperms ' = $file->getperms (),//file permissions
' Getrealpath ' = $file->getrealpath (),//File absolute path
' GetSize ' = $file->getsize (),//File size, unit byte
' GetType ' = $file->gettype (),//File type files dir link
' Isdir ' = $file->isdir (),//Is directory
' Isfile ' = $file->isfile (),//Whether it is a file
' Islink ' = $file->islink (),//is a shortcut link
' IsExecutable ' = $file->isexecutable (),//whether executable
' IsReadable ' = $file->isreadable (),//Is readable
' IsWritable ' = $file->iswritable (),//writable
));
Splfileobject inherits Splfileinfo and implements Recursiveiterator, Seekableiterator interface for file traversal, lookup, operation
Traverse:
Copy the Code code as follows:
try {
foreach (New Splfileobject (' Foo-bar.txt ') as $line) {
Echo $line;
}
} catch (Exception $e) {
echo $e->getmessage ();
}
Find the specified line:
Copy the Code code as follows:
try {
$file = new Splfileobject (' Foo-bar.txt ');
$file->seek (2);
echo $file->current ();
} catch (Exception $e) {
echo $e->getmessage ();
}
Write to CSV file:
Copy the Code code as follows:
$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);
}