Класс SplFileObject

(PHP 5 >= 5.1.0, PHP 7)

Введение

Класс SplFileObject предоставляет объектно-ориентированный интерфейс для файлов.

Обзор классов

SplFileObject extends SplFileInfo implements RecursiveIterator , SeekableIterator {
/* Константы */
const integer DROP_NEW_LINE = 1 ;
const integer READ_AHEAD = 2 ;
const integer SKIP_EMPTY = 4 ;
const integer READ_CSV = 8 ;
/* Методы */
public __construct ( string $filename [, string $open_mode = "r" [, bool $use_include_path = false [, resource $context ]]] )
public string|array current ( void )
public bool eof ( void )
public bool fflush ( void )
public string fgetc ( void )
public array fgetcsv ([ string $delimiter = "," [, string $enclosure = "\"" [, string $escape = "\\" ]]] )
public string fgets ( void )
public string fgetss ([ string $allowable_tags ] )
public bool flock ( int $operation [, int &$wouldblock ] )
public int fpassthru ( void )
public int fputcsv ( array $fields [, string $delimiter = "," [, string $enclosure = '"' ]] )
public string fread ( int $length )
public mixed fscanf ( string $format [, mixed &$... ] )
public int fseek ( int $offset [, int $whence = SEEK_SET ] )
public array fstat ( void )
public int ftell ( void )
public bool ftruncate ( int $size )
public int fwrite ( string $str [, int $length ] )
public void getChildren ( void )
public array getCsvControl ( void )
public int getFlags ( void )
public int getMaxLineLen ( void )
public bool hasChildren ( void )
public int key ( void )
public void next ( void )
public void rewind ( void )
public void seek ( int $line_pos )
public void setCsvControl ([ string $delimiter = "," [, string $enclosure = "\"" [, string $escape = "\\" ]]] )
public void setFlags ( int $flags )
public void setMaxLineLen ( int $max_len )
public void __toString ( void )
public bool valid ( void )
/* Наследуемые методы */
public SplFileInfo::__construct ( string $file_name )
public int SplFileInfo::getATime ( void )
public string SplFileInfo::getBasename ([ string $suffix ] )
public int SplFileInfo::getCTime ( void )
public string SplFileInfo::getExtension ( void )
public SplFileInfo SplFileInfo::getFileInfo ([ string $class_name ] )
public string SplFileInfo::getFilename ( void )
public int SplFileInfo::getGroup ( void )
public int SplFileInfo::getInode ( void )
public string SplFileInfo::getLinkTarget ( void )
public int SplFileInfo::getMTime ( void )
public int SplFileInfo::getOwner ( void )
public string SplFileInfo::getPath ( void )
public SplFileInfo SplFileInfo::getPathInfo ([ string $class_name ] )
public string SplFileInfo::getPathname ( void )
public int SplFileInfo::getPerms ( void )
public string SplFileInfo::getRealPath ( void )
public int SplFileInfo::getSize ( void )
public string SplFileInfo::getType ( void )
public bool SplFileInfo::isDir ( void )
public bool SplFileInfo::isExecutable ( void )
public bool SplFileInfo::isFile ( void )
public bool SplFileInfo::isLink ( void )
public bool SplFileInfo::isReadable ( void )
public bool SplFileInfo::isWritable ( void )
public SplFileObject SplFileInfo::openFile ([ string $open_mode = "r" [, bool $use_include_path = false [, resource $context = NULL ]]] )
public void SplFileInfo::setFileClass ([ string $class_name = "SplFileObject" ] )
public void SplFileInfo::setInfoClass ([ string $class_name = "SplFileInfo" ] )
public void SplFileInfo::__toString ( void )
}

Предопределенные константы

SplFileObject::DROP_NEW_LINE

Удаляет символы переноса в конце строки.

SplFileObject::READ_AHEAD

Читает при использовании функций rewind/next.

SplFileObject::SKIP_EMPTY

Пропускает пустые строки с файле. Для правильной работы требуется включить флаг READ_AHEAD.

SplFileObject::READ_CSV

Читает строки в формате CSV.

Список изменений

Версия Описание
5.3.9 Значение SplFileObject::SKIP_EMPTY изменено на 4. Раньше значение было равным 6.

Содержание

Коментарии

Note that this class has a private (and thus, not documented) property that holds the file pointer. Combine this with the fact that there is no method to close the file handle, and you get into situations where you are not able to delete the file with unlink(), etc., because an SplFileObject still has a handle open.

To get around this issue, delete the SplFileObject like this:

---------------------------------------------------------------------
<?php
print "Declaring file object\n";
$file = new SplFileObject('example.txt');

print 
"Trying to delete file...\n";
unlink('example.txt');

print 
"Closing file object\n";
$file null;

print 
"Deleting file...\n";
unlink('example.txt');

print 
'File deleted!';
?>
---------------------------------------------------------------------

which will output:

---------------------------------------------------------------------
Declaring file object 
Trying to delete file... 

Warning: unlink(example.txt): Permission denied in file.php on line 6
Closing file object 
Deleting file... 
File deleted!
---------------------------------------------------------------------
2013-09-05 16:46:45
http://php5.kiev.ua/manual/ru/class.splfileobject.html
If you want to skip blank lines when reading a CSV file, you need *all * the flags:

$file->setFlags(SplFileObject::READ_CSV | SplFileObject::READ_AHEAD | SplFileObject::SKIP_EMPTY | SplFileObject::DROP_NEW_LINE);
2014-08-16 23:35:46
http://php5.kiev.ua/manual/ru/class.splfileobject.html
Complimenting marcus at synchromedia dot co dot uk comment, you can also do something like this:

<?php

// create a SplFileObject for reading - note that there are no flags
$file = new SplFileObject('/path/to/file''r');

// iterate over its contents
while (!$file->eof()) {
   
// get the current line
   
$line  $file->fgets();

   
// trim it, and then check if its empty
   
if (empty(trim($line))) {
       
// skips the current iteration
       
continue;
    }
}

While 
this may seem like a overkill for such thingit allows you to do some processing with the empty lines that might come (I had to do this mostly because I needed to count empty lines instead of just skipping them). Since it also trims the line before checking if it's empty, you won't get lines composed only of empty spaces (I don't know if the flags also make it trim the content before checking it).
2021-02-04 20:00:27
http://php5.kiev.ua/manual/ru/class.splfileobject.html
with php 8.3, with or without SplFileObject::DROP_NEW_LINE, you get an array with empty values at the end.
2024-03-16 21:32:18
http://php5.kiev.ua/manual/ru/class.splfileobject.html

    Поддержать сайт на родительском проекте КГБ