PHP.mk документација

SplFileObject

Почист и полокален преглед на PHP референцата, со задржана структура од PHP.net и подобра читливост за примери, секции и белешки.

class.splfileobject.php PHP.net прокси Преводот се освежува
Оригинал на PHP.net
Патека class.splfileobject.php Локална патека за оваа страница.
Извор php.net/manual/en Оригиналниот HTML се реупотребува и локално се стилизира.
Режим Прокси + превод во позадина Кодовите, табелите и белешките остануваат читливи во истиот тек.
SplFileObject

Референца за `class.splfileobject.php` со подобрена типографија и навигација.

class.splfileobject.php

Класата SplFileObject

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

Вовед

Класата SplFileObject нуди објектно-ориентиран интерфејс за датотека.

Синопсис на класата

class SplFileObject extends SplFileInfo implements RecursiveIterator, SeekableIterator {
/* Константи */
public const int DROP_NEW_LINE;
public const int READ_AHEAD;
public const int SKIP_EMPTY;
public const int READ_CSV;
/* Методи */
public __construct(
         string $filename,
         string $mode = FilesystemIterator::KEY_AS_PATHNAME | FilesystemIterator::CURRENT_AS_FILEINFO,
         bool $useIncludePath = false,
         ?resource $context = null
)
public eof(): bool
public fflush(): bool
public fgetc(): string|false
public fgetcsv(string $separator = ",", string $enclosure = "\"", string $escape = "\\"): array|false
public fgets(): string
public fgetss(string $allowable_tags = ?): string
public flock(int $operation, int &$wouldBlock = null): bool
public fpassthru(): int
public fputcsv(
         array $fields,
         string $separator = ",",
         string $enclosure = "\"",
         string $escape = "\\",
         string $eol Форматира линија како CSV и ја пишува во датотечен покажувач
): int|false
public fread(int $length): string|false
public fscanf(string $format, mixed &...$vars): array|int|null
public fseek(int $offset, int $whence = SEEK_SET): int
public fstat(): array
public ftell(): int|false
public ftruncate(int $size): bool
public fwrite(string $data, ?int $length = null): int|false
public getChildren(): null
public getFlags(): int
public getMaxLineLen(): int
public hasChildren(): false
public key(): int
public next(): void
public rewind(): void
public seek(int $line): void
public setCsvControl(string $separator = ",", string $enclosure = "\"", string $escape = "\\"): void
public setFlags(int $flags): void
public setMaxLineLen(int $maxLength): void
public __toString(): string
public valid(): bool
/* Наследени методи */
public SplFileInfo::getBasename(string $suffix = ""): string
public SplFileInfo::openFile(string $mode = FilesystemIterator::KEY_AS_PATHNAME | FilesystemIterator::CURRENT_AS_FILEINFO, bool $useIncludePath = false, ?resource $context = null): SplFileObject
public SplFileInfo::setFileClass(string $class = SplFileObject::class): void
public SplFileInfo::setInfoClass(string $class = SplFileInfo::class): void
}

Претходно дефинирани константи

SplFileObject::DROP_NEW_LINE

Отфрли нови редови на крајот од редот.

SplFileObject::READ_AHEAD

Читај при премотување/следно.

SplFileObject::SKIP_EMPTY

Прескокнува празни редови во датотеката. Ова бара READ_AHEAD знаменцето да биде овозможено, за да работи како што се очекува.

SplFileObject::READ_CSV

Читај редови како CSV редови.

Содржина

Белешки од корисници 4 белешки

Lars Gyrup Brink Nielsen
12 години пред
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!
---------------------------------------------------------------------
clcollie на mindspring точка com
пред 11 години
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);
contact at trimal dot in
пред 2 години
with php 8.3, with or without SplFileObject::DROP_NEW_LINE, you get an array with empty values at the end.
rlazarotto15+не+ми+спамирај на gmail точка ком
пред 5 години
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 thing, it 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).
Навигација

Прелистувај сродни теми и функции.

На оваа страница

Автоматски outline од активната документација.

Насловите ќе се појават тука по вчитување.

Попрегледно читање

Примерите, changelog табелите и user notes се визуелно издвоени за да не се губат во долгата содржина.

Брз совет Користи го outline-от Скокни директно на главните секции од активната страница.
Извор Оригиналниот линк останува достапен Кога ти треба целосен upstream context, отвори го PHP.net во нов tab.