This article mainly introduces the PHP SPL standard library file operations (Splfileinfo and Splfileobject) instances, this article explains Splfileinfo used to obtain file details, Splfileobject traversal, find the specified row, Write CSV file and so on content, need friends can refer to the following
PHP SPL provides splfileinfo and splfileobject two classes to handle file operations.
Splfileinfo used to get file details:
The code is as follows:
$file = new Splfileinfo (' Foo-bar.txt ');
Print_r Array (
' Getatime ' => $file->getatime (),//Last visit time
' Getbasename ' => $file->getbasename (),//Get path-free basename
' Getctime ' => $file->getctime (),//Get Inode modification time
' GetExtension ' => $file->getextension (),//file name extension
' GetFileName ' => $file->getfilename (),//Get filename
' Getgroup ' => $file->getgroup (),//Get file group
' Getinode ' => $file->getinode (),//Get file Inode
' Getlinktarget ' => $file->getlinktarget (),//Get File link destination file
' Getmtime ' => $file->getmtime (),//Get Last modification time
' GetOwner ' => $file->getowner (),//File owner
' GetPath ' => $file->getpath (),//file path without file name
' GetPathInfo ' => $file->getpathinfo (),//Splfileinfo object of Superior 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 (),//Files type file dir link
' Isdir ' => $file->isdir (),//Whether it is a directory
' Isfile ' => $file->isfile (),//Whether it is a file
' Islink ' => $file->islink (),//Whether it is a shortcut link
' IsExecutable ' => $file->isexecutable (),//whether executable
' IsReadable ' => $file->isreadable (),//readable
' IsWritable ' => $file->iswritable (),//Whether it can be written
));
Splfileobject inherits Splfileinfo and implements Recursiveiterator, Seekableiterator interface for traversing, locating, and manipulating files
Traverse:
The code is as follows:
try {
foreach (New Splfileobject (' Foo-bar.txt ') as $line) {
Echo $line;
}
catch (Exception $e) {
echo $e->getmessage ();
}
Find the specified line:
The code is as follows:
try {
$file = new Splfileobject (' Foo-bar.txt ');
$file->seek (2);
echo $file->current ();
catch (Exception $e) {
echo $e->getmessage ();
}
To write to a CSV file:
The code is 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);
}