The SplFileObject class (PHP 5 >= 5.1.0, PHP 7)

The SplFileObject class offers an object oriented interface for a file.

Sinopse da classe

SplFileObject extends implements , {
/* Constantes */
const int = 1 ;
const int = 2 ;
const int = 4 ;
const int = 8 ;
/* Métodos */
public ( string $filename [, string $open_mode = "r" [, bool $use_include_path = FALSE [, resource $context ]]] )
public ( ) : string|array
public ( ) : bool
public ( ) : bool
public ( ) : string
public ([ string $delimiter = "," [, string $enclosure = "\"" [, string $escape = "\\" ]]] ) : array
public ( ) : string
public ([ string $allowable_tags ] ) : string
public ( int $operation [, int &$wouldblock ] ) : bool
public ( ) : int
public ( array $fields [, string $delimiter = "," [, string $enclosure = '"' [, string $escape = "\\" ]]] ) : int|false
public ( int $length ) : string|false
public ( string $format , &...$vars ) :
public ( int $offset [, int $whence = SEEK_SET ] ) : int
public ( ) : array
public ( ) : int
public ( int $size ) : bool
public ( string $str [, int $length ] ) : int
public ( ) : void
public ( ) : array
public ( ) : int
public ( ) : int
public ( ) : bool
public ( ) : int
public ( ) : void
public ( ) : void
public ( int $line_pos ) : void
public ([ string $delimiter = "," [, string $enclosure = "\"" [, string $escape = "\\" ]]] ) : void
public ( int $flags ) : void
public ( int $max_len ) : void
public ( ) : bool
/* Métodos herdados */
public ( ) : int
public ([ string $suffix ] ) : string
public ( ) : int
public ( ) : string
public ([ string $class_name ] ) :
public ( ) : string
public ( ) : int
public ( ) : int
public ( ) : string
public ( ) : int
public ( ) : int
public ( ) : string
public ([ string $class_name ] ) :
public ( ) : string
public ( ) : int
public ( ) : string
public ( ) : int
public ( ) : string
public ( ) : bool
public ( ) : bool
public ( ) : bool
public ( ) : bool
public ( ) : bool
public ( ) : bool
public ([ string $open_mode = "r" [, bool $use_include_path = FALSE [, resource $context = NULL ]]] ) :
public ([ string $class_name = "SplFileObject" ] ) : void
public ([ string $class_name = "SplFileInfo" ] ) : void
public ( ) : string
}

Constantes pré-definidas

SplFileObject::DROP_NEW_LINE

Drop newlines at the end of a line.

SplFileObject::READ_AHEAD

Read on rewind/next.

SplFileObject::SKIP_EMPTY

Skips empty lines in the file. This requires the READ_AHEAD flag be enabled, to work as expected.

SplFileObject::READ_CSV

Read lines as CSV rows.

Changelog

Versão Descrição
5.3.9 SplFileObject::SKIP_EMPTY value changed to 4. Previously, value was 6.

SplFileObject::__construct

(PHP 5 >= 5.1.0, PHP 7)

SplFileObject::__constructConstruct a new file object

Descrição

public SplFileObject::__construct ( string $filename [, string $open_mode = "r" [, bool $use_include_path = FALSE [, resource $context ]]] )

Construct a new file object.

Parâmetros

filename

The file to read.

Dica

Uma URL pode ser utilizada como um nome de arquivo se estiver ativo. Veja para mais detalhes em como especificar URLs como nome de arquivo. Veja também the para informações sobre que capacidades cada wrapper tem, notas de uso e informações sobre variáveis predefinidas fornecidas.

open_mode

The mode in which to open the file. See for a list of allowed modes.

use_include_path

Whether to search in the for filename.

context

A valid context resource created with .

Valor Retornado

Não há valor retornado.

Erros

Throws a if the filename cannot be opened.

Throws a if the filename is a directory.

Exemplos

Exemplo #1 SplFileObject::__construct() example

This example opens the current file and iterates over its contents line by line.

<?php
$file 
= new SplFileObject(__FILE__);
foreach (
$file as $line_num => $line) {
    echo 
"Line $line_num is $line";
}
?>

O exemplo acima irá imprimir algo similar à:

Line 0 is <?php
Line 1 is $file = new SplFileObject(__FILE__);
Line 2 is foreach ($file as $line_num => $line) {
Line 3 is     echo "Line $line_num is $line";
Line 4 is }
Line 5 is ?>

Veja Também



SplFileObject::current

(PHP 5 >= 5.1.0, PHP 7)

SplFileObject::currentRetrieve current line of file

Descrição

public SplFileObject::current ( ) : string|array

Retrieves the current line of the file.

Parâmetros

Esta função não possui parâmetros.

Valor Retornado

Retrieves the current line of the file. If the SplFileObject::READ_CSV flag is set, this method returns an array containing the current line parsed as CSV data.

Exemplos

Exemplo #1 SplFileObject::current() example

<?php
$file 
= new SplFileObject(__FILE__);
foreach (
$file as $k => $line) {
   echo (
$file->key() + 1) . ': ' . $file->current();
}
?>

O exemplo acima irá imprimir algo similar à:

1: <?php
2: $file = new SplFileObject(__FILE__);
3: foreach ($file as $line) {
4:     echo ($file->key() + 1) . ': ' . $file->current();
5: }
6: ?>

Veja Também



SplFileObject::eof

(PHP 5 >= 5.1.0, PHP 7)

SplFileObject::eofReached end of file

Descrição

public SplFileObject::eof ( ) : bool

Determine whether the end of file has been reached

Parâmetros

Esta função não possui parâmetros.

Valor Retornado

Returns TRUE if file is at EOF, FALSE otherwise.

Exemplos

Exemplo #1 SplFileObject::eof() example

<?php
$file 
= new SplFileObject("fruits.txt");
while ( ! 
$file->eof()) {
    echo 
$file->fgets();
}
?>

O exemplo acima irá imprimir algo similar à:

apple
banana
cherry
date
elderberry

Veja Também



SplFileObject::fflush

(PHP 5 >= 5.1.0, PHP 7)

SplFileObject::fflushFlushes the output to the file

Descrição

public SplFileObject::fflush ( ) : bool

Forces a write of all buffered output to the file.

Parâmetros

Esta função não possui parâmetros.

Valor Retornado

Retorna TRUE em caso de sucesso ou FALSE em caso de falha.

Exemplos

Exemplo #1 SplFileObject::fflush() example

<?php
$file 
= new SplFileObject('misc.txt', 'r+');
$file->rewind();
$file->fwrite("Foo");
$file->fflush();
$file->ftruncate($file->ftell());
?>

Veja Também



SplFileObject::fgetc

(PHP 5 >= 5.1.0, PHP 7)

SplFileObject::fgetcGets character from file

Descrição

public SplFileObject::fgetc ( ) : string

Gets a character from the file.

Parâmetros

Esta função não possui parâmetros.

Valor Retornado

Returns a string containing a single character read from the file or FALSE on EOF.

Aviso

Esta função pode retornar o booleano FALSE, mas também pode retornar um valor não-booleano que pode ser avaliado como FALSE, como 0 ou "". Leia a seção em para maiores informações. Utilize o para testar o valor retornado por esta função.

Exemplos

Exemplo #1 SplFileObject::fgetc() example

<?php
$file 
= new SplFileObject('file.txt');
while (
false !== ($char = $file->fgetc())) {
    echo 
"$char\n";
}
?>

Veja Também



SplFileObject::fgetcsv

(PHP 5 >= 5.1.0, PHP 7)

SplFileObject::fgetcsvGets line from file and parse as CSV fields

Descrição

public SplFileObject::fgetcsv ([ string $delimiter = "," [, string $enclosure = "\"" [, string $escape = "\\" ]]] ) : array

Gets a line from the file which is in CSV format and returns an array containing the fields read.

Nota:

The locale settings are taken into account by this function. If LC_CTYPE is e.g. en_US.UTF-8, files in one-byte encodings may be read wrongly by this function.

Parâmetros

delimiter

The field delimiter (one character only). Defaults as a comma or the value set using .

enclosure

The field enclosure character (one character only). Defaults as a double quotation mark or the value set using .

escape

The escape character (at most one character). Defaults as a backslash (\) or the value set using . An empty string ("") disables the proprietary escape mechanism.

Nota: Usually an enclosure character is escpaped inside a field by doubling it; however, the escape character can be used as an alternative. So for the default parameter values "" and \" have the same meaning. Other than allowing to escape the enclosure character the escape character has no special meaning; it isn't even meant to escape itself.

Valor Retornado

Returns an indexed array containing the fields read, or FALSE on error.

Nota:

A blank line in a CSV file will be returned as an array comprising a single NULL field unless using SplFileObject::SKIP_EMPTY | SplFileObject::DROP_NEW_LINE, in which case empty lines are skipped.

Changelog

Versão Descrição
7.4.0 The escape parameter now also accepts an empty string to disable the proprietary escape mechanism.

Exemplos

Exemplo #1 SplFileObject::fgetcsv() example

<?php
$file 
= new SplFileObject("data.csv");
while (!
$file->eof()) {
    
var_dump($file->fgetcsv());
}
?>

Exemplo #2 SplFileObject::READ_CSV example

<?php
$file 
= new SplFileObject("animals.csv");
$file->setFlags(SplFileObject::READ_CSV);
foreach (
$file as $row) {
    list(
$animal, $class, $legs) = $row;
    
printf("A %s is a %s with %d legs\n", $animal, $class, $legs);
}
?>

Contents of animals.csv

crocodile,reptile,4
dolphin,mammal,0
duck,bird,2
koala,mammal,4
salmon,fish,0

O exemplo acima irá imprimir algo similar à:

A crocodile is a reptile with 4 legs
A dolphin is a mammal with 0 legs
A duck is a bird with 2 legs
A koala is a mammal with 4 legs
A salmon is a fish with 0 legs

Veja Também



SplFileObject::fgets

(PHP 5 >= 5.1.0, PHP 7)

SplFileObject::fgetsGets line from file

Descrição

public SplFileObject::fgets ( ) : string

Gets a line from the file.

Parâmetros

Esta função não possui parâmetros.

Valor Retornado

Returns a string containing the next line from the file, or FALSE on error.

Erros

Throws a if the file cannot be read.

Exemplos

Exemplo #1 SplFileObject::fgets() example

This example simply outputs the contents of file.txt line-by-line.

<?php
$file 
= new SplFileObject("file.txt");
while (!
$file->eof()) {
    echo 
$file->fgets();
}
?>

Veja Também



SplFileObject::fgetss

(PHP 5 >= 5.1.0, PHP 7)

SplFileObject::fgetssGets line from file and strip HTML tags

Aviso

This function has been DEPRECATED as of PHP 7.3.0. Relying on this function is highly discouraged.

Descrição

public SplFileObject::fgetss ([ string $allowable_tags ] ) : string

Identical to , except that SplFileObject::fgetss() attempts to strip any HTML and PHP tags from the text it reads. The function retains the parsing state from call to call, and as such is not equivalent to calling on the return value of .

Parâmetros

allowable_tags

Optional parameter to specify tags which should not be stripped.

Valor Retornado

Returns a string containing the next line of the file with HTML and PHP code stripped, or FALSE on error.

Exemplos

Exemplo #1 SplFileObject::fgetss() example

<?php
$str 
= <<<EOD
<html><body>
 <p>Welcome! Today is the <?php echo(date('jS')); ?> of <?= date('F'); ?>.</p>
</body></html>
Text outside of the HTML block.
EOD;
file_put_contents("sample.php", $str);

$file = new SplFileObject("sample.php");
while (!
$file->eof()) {
    echo 
$file->fgetss();
}
?>

O exemplo acima irá imprimir algo similar à:


 Welcome! Today is the  of .

Text outside of the HTML block.

Veja Também



SplFileObject::flock

(PHP 5 >= 5.1.0, PHP 7)

SplFileObject::flockPortable file locking

Descrição

public SplFileObject::flock ( int $operation [, int &$wouldblock ] ) : bool

Locks or unlocks the file in the same portable way as .

Parâmetros

operation

operation is one of the following:

  • LOCK_SH to acquire a shared lock (reader).
  • LOCK_EX to acquire an exclusive lock (writer).
  • LOCK_UN to release a lock (shared or exclusive).

It is also possible to add LOCK_NB as a bitmask to one of the above operations, if should not block during the locking attempt.

wouldblock

Set to TRUE if the lock would block (EWOULDBLOCK errno condition).

Valor Retornado

Retorna TRUE em caso de sucesso ou FALSE em caso de falha.

Exemplos

Exemplo #1 SplFileObject::flock() example

<?php
$file 
= new SplFileObject("/tmp/lock.txt", "w");
if (
$file->flock(LOCK_EX)) { // do an exclusive lock
    
$file->ftruncate(0);     // truncate file
    
$file->fwrite("Write something here\n");
    
$file->flock(LOCK_UN);   // release the lock    
} else {
    echo 
"Couldn't get the lock!";
}
?>

Veja Também

  • - Monitor de travamento de arquivos portátil


SplFileObject::fpassthru

(PHP 5 >= 5.1.0, PHP 7)

SplFileObject::fpassthruOutput all remaining data on a file pointer

Descrição

public SplFileObject::fpassthru ( ) : int

Reads to EOF on the given file pointer from the current position and writes the results to the output buffer.

You may need to call to reset the file pointer to the beginning of the file if you have already written data to the file.

Parâmetros

Esta função não possui parâmetros.

Valor Retornado

Returns the number of characters read from handle and passed through to the output.

Exemplos

Exemplo #1 SplFileObject::fpassthru() example

<?php

// Open the file in binary mode
$file = new SplFileObject("./img/ok.png", "rb");

// Send the right headers
header("Content-Type: image/png");
header("Content-Length: " . $file->getSize());

// Dump the picture and end script
$file->fpassthru();
exit;

?>

Veja Também

  • - Imprime todo os dados restantes de um ponteiro de arquivo


SplFileObject::fputcsv

(PHP 5 >= 5.4.0, PHP 7)

SplFileObject::fputcsvWrite a field array as a CSV line

Descrição

public SplFileObject::fputcsv ( array $fields [, string $delimiter = "," [, string $enclosure = '"' [, string $escape = "\\" ]]] ) : int|false

Writes the fields array to the file as a CSV line.

Parâmetros

fields

An array of values.

delimiter

The optional delimiter parameter sets the field delimiter (one character only).

enclosure

The optional enclosure parameter sets the field enclosure (one character only).

escape

The optional escape parameter sets the escape character (at most one character). An empty string ("") disables the proprietary escape mechanism.

Nota:

If an enclosure character is contained in a field, it will be escaped by doubling it, unless it is immediately preceded by an escape_char.

Valor Retornado

Returns the length of the written string ou FALSE em caso de falha.

Returns FALSE, and does not write the CSV line to the file, if the delimiter or enclosure parameter is not a single character.

Erros

An E_WARNING level error is issued if the delimiter or enclosure parameter is not a single character.

Changelog

Versão Descrição
7.4.0 The escape parameter now also accepts an empty string to disable the proprietary escape mechanism.
5.5.21, 5.6.5 Added the escape parameter.

Exemplos

Exemplo #1 SplFileObject::fputcsv() example

<?php

$list 
= array (
    array(
'aaa', 'bbb', 'ccc', 'dddd'),
    array(
'123', '456', '789'),
    array(
'"aaa"', '"bbb"')
);

$file = new SplFileObject('file.csv', 'w');

foreach (
$list as $fields) {
    
$file->fputcsv($fields);
}

?>

The above example will write the following to file.csv:

aaa,bbb,ccc,dddd
123,456,789
"""aaa""","""bbb"""

Veja Também



SplFileObject::fread

(PHP 5 >= 5.5.11, PHP 7)

SplFileObject::freadRead from file

Descrição

public SplFileObject::fread ( int $length ) : string|false

Reads the given number of bytes from the file.

Parâmetros

length

The number of bytes to read.

Valor Retornado

Returns the string read from the file ou FALSE em caso de falha.

Exemplos

Exemplo #1 SplFileObject::fread() example

<?php
// Get contents of a file into a string
$filename = "/usr/local/something.txt";
$file = new SplFileObject($filename, "r");
$contents = $file->fread($file->getSize());
?>

Notas

Nota:

Note that SplFileObject::fread() reads from the current position of the file pointer. Use to find the current position of the pointer and (or ) to rewind the pointer position.

Veja Também

  • - Leitura binary-safe de arquivo


SplFileObject::fscanf

(PHP 5 >= 5.1.0, PHP 7)

SplFileObject::fscanfParses input from file according to a format

Descrição

public SplFileObject::fscanf ( string $format , &...$vars ) :

Reads a line from the file and interprets it according to the specified format, which is described in the documentation for .

Any whitespace in the format string matches any whitespace in the line from the file. This means that even a tab \t in the format string can match a single space character in the input stream.

Parâmetros

format

The format string is composed of zero or more directives: ordinary characters (excluding %) that are copied directly to the result and conversion specifications, each of which results in fetching its own parameter.

A conversion specification follows this prototype: %[argnum$][flags][width][.precision]specifier.

Argnum

An integer followed by a dollar sign $, to specify which number argument to treat in the conversion.

Flags
Flag Descrição
- Left-justify within the given field width; Right justification is the default
+ Prefix positive numbers with a plus sign +; Default only negative are prefixed with a negative sign.
(space) Pads the result with spaces. This is the default.
0 Only left-pads numbers with zeros. With s specifiers this can also right-pad with zeros.
'(char) Pads the result with the character (char).

Width

An integer that says how many characters (minimum) this conversion should result in.

Precision

A period . followed by an integer who's meaning depends on the specifier:

  • For e, E, f and F specifiers: this is the number of digits to be printed after the decimal point (by default, this is 6).
  • For g and G specifiers: this is the maximum number of significant digits to be printed.
  • For s specifier: it acts as a cutoff point, setting a maximum character limit to the string.

Nota: If the period is specified without an explicit value for precision, 0 is assumed.

Nota: Attempting to use a position specifier greater than PHP_INT_MAX will generate warnings.

Specifiers
Specifier Descrição
% A literal percent character. No argument is required.
b The argument is treated as an integer and presented as a binary number.
c The argument is treated as an integer and presented as the character with that ASCII.
d The argument is treated as an integer and presented as a (signed) decimal number.
e The argument is treated as scientific notation (e.g. 1.2e+2). The precision specifier stands for the number of digits after the decimal point since PHP 5.2.1. In earlier versions, it was taken as number of significant digits (one less).
E Like the e specifier but uses uppercase letter (e.g. 1.2E+2).
f The argument is treated as a float and presented as a floating-point number (locale aware).
F The argument is treated as a float and presented as a floating-point number (non-locale aware). Available as of PHP 5.0.3.
g

General format.

Let P equal the precision if nonzero, 6 if the precision is omitted, or 1 if the precision is zero. Then, if a conversion with style E would have an exponent of X:

If P > X ≥ −4, the conversion is with style f and precision P − (X + 1). Otherwise, the conversion is with style e and precision P − 1.

G Like the g specifier but uses E and f.
o The argument is treated as an integer and presented as an octal number.
s The argument is treated and presented as a string.
u The argument is treated as an integer and presented as an unsigned decimal number.
x The argument is treated as an integer and presented as a hexadecimal number (with lowercase letters).
X The argument is treated as an integer and presented as a hexadecimal number (with uppercase letters).
Aviso

The c type specifier ignores padding and width

Aviso

Attempting to use a combination of the string and width specifiers with character sets that require more than one byte per character may result in unexpected results

Variables will be co-erced to a suitable type for the specifier:

Type Handling
Type Specifiers
string s
integer d, u, c, o, x, X, b
double g, G, e, E, f, F
vars

The optional assigned values.

Valor Retornado

If only one parameter is passed to this method, the values parsed will be returned as an array. Otherwise, if optional parameters are passed, the function will return the number of assigned values. The optional parameters must be passed by reference.

Exemplos

Exemplo #1 SplFileObject::fscanf() example

<?php
$file 
= new SplFileObject("misc.txt");
while (
$userinfo = $file->fscanf("%s %s %s")) {
    list (
$name, $profession, $countrycode) = $userinfo;
    
// Do something with $name $profession $countrycode
}
?>

Contents of users.txt

javier   argonaut    pe
hiroshi  sculptor    jp
robert   slacker     us
luigi    florist     it

Veja Também

  • - Interpreta a leitura de um arquivo de acordo com um formato
  • - Interpreta a entrada de uma string de acordo com um formato
  • - Mostra uma string formatada
  • - Retorna a string formatada


SplFileObject::fseek

(PHP 5 >= 5.1.0, PHP 7)

SplFileObject::fseekSeek to a position

Descrição

public SplFileObject::fseek ( int $offset [, int $whence = SEEK_SET ] ) : int

Seek to a position in the file measured in bytes from the beginning of the file, obtained by adding offset to the position specified by whence.

Parâmetros

offset

The offset. A negative value can be used to move backwards through the file which is useful when SEEK_END is used as the whence value.

whence

whence values are:

  • SEEK_SET - Set position equal to offset bytes.
  • SEEK_CUR - Set position to current location plus offset.
  • SEEK_END - Set position to end-of-file plus offset.

If whence is not specified, it is assumed to be SEEK_SET.

Valor Retornado

Returns 0 if the seek was successful, -1 otherwise. Note that seeking past EOF is not considered an error.

Exemplos

Exemplo #1 SplFileObject::fseek() example

<?php
$file 
= new SplFileObject("somefile.txt");

// Read first line
$data = $file->fgets();

// Move back to the beginning of the file
// Same as $file->rewind();
$file->fseek(0);
?>

Veja Também

  • - Procura (seeks) em um ponteiro de arquivo


SplFileObject::fstat

(PHP 5 >= 5.1.0, PHP 7)

SplFileObject::fstatGets information about the file

Descrição

public SplFileObject::fstat ( ) : array

Gathers the statistics of the file. Behaves identically to .

Parâmetros

Esta função não possui parâmetros.

Valor Retornado

Returns an array with the statistics of the file; the format of the array is described in detail on the manual page.

Exemplos

Exemplo #1 SplFileObject::fstat() example

<?php
$file 
= new SplFileObject("/etc/passwd");
$stat = $file->fstat();

// Print only the associative part
print_r(array_slice($stat, 13));

?>

O exemplo acima irá imprimir algo similar à:

Array
(
    [dev] => 771
    [ino] => 488704
    [mode] => 33188
    [nlink] => 1
    [uid] => 0
    [gid] => 0
    [rdev] => 0
    [size] => 1114
    [atime] => 1061067181
    [mtime] => 1056136526
    [ctime] => 1056136526
    [blksize] => 4096
    [blocks] => 8
)

Veja Também

  • - Lê informações sobre um arquivo usando um ponteiro de arquivo aberto
  • - Obtem informações sobre um arquivo


SplFileObject::ftell

(PHP 5 >= 5.1.0, PHP 7)

SplFileObject::ftellReturn current file position

Descrição

public SplFileObject::ftell ( ) : int

Returns the position of the file pointer which represents the current offset in the file stream.

Parâmetros

Esta função não possui parâmetros.

Valor Retornado

Returns the position of the file pointer as an integer, or FALSE on error.

Exemplos

Exemplo #1 SplFileObject::ftell() example

<?php
$file 
= new SplFileObject("/etc/passwd");

// Read first line
$data = $file->fgets();

// Where are we?
echo $file->ftell();
?>

Veja Também

  • - Retorna a posição de leitura/gravação do ponteiro do arquivo


SplFileObject::ftruncate

(PHP 5 >= 5.1.0, PHP 7)

SplFileObject::ftruncateTruncates the file to a given length

Descrição

public SplFileObject::ftruncate ( int $size ) : bool

Truncates the file to size bytes.

Parâmetros

size

The size to truncate to.

Nota:

If size is larger than the file it is extended with null bytes.

If size is smaller than the file, the extra data will be lost.

Valor Retornado

Retorna TRUE em caso de sucesso ou FALSE em caso de falha.

Exemplos

Exemplo #1 SplFileObject::ftruncate() example

<?php
// Create file containing "Hello World!"
$file = new SplFileObject("/tmp/ftruncate", "w+");
$file->fwrite("Hello World!");

// Truncate to 5 bytes
$file->ftruncate(5);

// Rewind and read data
$file->rewind();
echo 
$file->fgets();
?>

O exemplo acima irá imprimir algo similar à:

Hello

Veja Também

  • - Reduz um arquivo a um tamanho especificado


SplFileObject::fwrite

(PHP 5 >= 5.1.0, PHP 7)

SplFileObject::fwriteWrite to file

Descrição

public SplFileObject::fwrite ( string $str [, int $length ] ) : int

Writes the contents of string to the file

Parâmetros

str

The string to be written to the file.

length

If the length argument is given, writing will stop after length bytes have been written or the end of string is reached, whichever comes first.

Valor Retornado

Returns the number of bytes written, or FALSE on error.

Changelog

Versão Descrição
7.4.0 The function now returns FALSE instead of zero on failure.

Exemplos

Exemplo #1 SplFileObject::fwrite() example

<?php
$file 
= new SplFileObject("fwrite.txt", "w");
$written = $file->fwrite("12345");
echo 
"Wrote $written bytes to file";
?>

O exemplo acima irá imprimir algo similar à:

Wrote 5 bytes to file

Veja Também

  • - Escrita binary-safe em arquivos


SplFileObject::getChildren

(PHP 5 >= 5.1.0, PHP 7)

SplFileObject::getChildrenNo purpose

Descrição

public SplFileObject::getChildren ( ) : void

An does not have children so this method returns NULL.

Parâmetros

Esta função não possui parâmetros.

Valor Retornado

Não há valor retornado.

Veja Também



SplFileObject::getCsvControl

(PHP 5 >= 5.2.0, PHP 7)

SplFileObject::getCsvControlGet the delimiter, enclosure and escape character for CSV

Descrição

public SplFileObject::getCsvControl ( ) : array

Gets the delimiter, enclosure and escape character used for parsing CSV fields.

Parâmetros

Esta função não possui parâmetros.

Valor Retornado

Returns an indexed array containing the delimiter, enclosure and escape character.

Changelog

Versão Descrição
7.4.0 The escape character can now be an empty string.
5.6.25, 7.0.10 Added the escape character to the returned array.

Exemplos

Exemplo #1 SplFileObject::getCsvControl() example

<?php
$file 
= new SplFileObject("data.txt");
print_r($file->getCsvControl());
?>

O exemplo acima irá imprimir algo similar à:

Array
(
    [0] => ,
    [1] => "
    [2] => \
)

Veja Também



SplFileObject::getCurrentLine

(PHP 5 >= 5.1.2, PHP 7)

SplFileObject::getCurrentLineAlias of

Descrição

Este método é um apelido para: .



SplFileObject::getFlags

(PHP 5 >= 5.1.0, PHP 7)

SplFileObject::getFlagsGets flags for the SplFileObject

Descrição

public SplFileObject::getFlags ( ) : int

Gets the flags set for an instance of SplFileObject as an int.

Parâmetros

Esta função não possui parâmetros.

Valor Retornado

Returns an int representing the flags.

Exemplos

Exemplo #1 SplFileObject::getFlags() example

<?php
$file 
= new SplFileObject(__FILE__, "r");

if (
$file->getFlags() & SplFileObject::SKIP_EMPTY) {
    echo 
"Skipping empty lines\n";
} else {
    echo 
"Not skipping empty lines\n";
}

$file->setFlags(SplFileObject::SKIP_EMPTY);

if (
$file->getFlags() & SplFileObject::SKIP_EMPTY) {
    echo 
"Skipping empty lines\n";
} else {
    echo 
"Not skipping empty lines\n";
}
?>

O exemplo acima irá imprimir algo similar à:

Not skipping empty lines
Skipping empty lines

Veja Também



SplFileObject::getMaxLineLen

(PHP 5 >= 5.1.0, PHP 7)

SplFileObject::getMaxLineLenGet maximum line length

Descrição

public SplFileObject::getMaxLineLen ( ) : int

Gets the maximum line length as set by .

Parâmetros

Esta função não possui parâmetros.

Valor Retornado

Returns the maximum line length if one has been set with , default is 0.

Exemplos

Exemplo #1 SplFileObject::getMaxLineLen() example

<?php
$file 
= new SplFileObject("file.txt");
var_dump($file->getMaxLineLen());

$file->setMaxLineLen(20);
var_dump($file->getMaxLineLen());
?>

O exemplo acima irá imprimir algo similar à:

int(0)
int(20)

Veja Também



SplFileObject::hasChildren

(PHP 5 >= 5.1.2, PHP 7)

SplFileObject::hasChildrenSplFileObject does not have children

Descrição

public SplFileObject::hasChildren ( ) : bool

An does not have children so this method always return FALSE.

Parâmetros

Esta função não possui parâmetros.

Valor Retornado

Returns FALSE

Veja Também



SplFileObject::key

(PHP 5 >= 5.1.0, PHP 7)

SplFileObject::keyGet line number

Descrição

public SplFileObject::key ( ) : int

Gets the current line number.

Nota:

This number may not reflect the actual line number in the file if is used to read fixed lengths of the file.

Parâmetros

Esta função não possui parâmetros.

Valor Retornado

Returns the current line number.

Exemplos

Exemplo #1 SplFileObject::key() example

<?php
$file 
= new SplFileObject("lipsum.txt");
foreach (
$file as $line) {
    echo 
$file->key() . ". " . $line;
}
?>

O exemplo acima irá imprimir algo similar à:

0. Lorem ipsum dolor sit amet, consectetur adipiscing elit.
1. Duis nec sapien felis, ac sodales nisl.
2. Lorem ipsum dolor sit amet, consectetur adipiscing elit.

Exemplo #2 SplFileObject::key() example with

<?php
$file 
= new SplFileObject("lipsum.txt");
$file->setMaxLineLen(20);
foreach (
$file as $line) {
    echo 
$file->key() . ". " . $line . "\n";
}
?>

O exemplo acima irá imprimir algo similar à:

0. Lorem ipsum dolor s
1. it amet, consectetu
2. r adipiscing elit.
3.

4. Duis nec sapien fel
5. is, ac sodales nisl
6. .

7. Lorem ipsum dolor s
8. it amet, consectetu
9. r adipiscing elit.

Veja Também



SplFileObject::next

(PHP 5 >= 5.1.0, PHP 7)

SplFileObject::nextRead next line

Descrição

public SplFileObject::next ( ) : void

Moves ahead to the next line in the file.

Parâmetros

Esta função não possui parâmetros.

Valor Retornado

Não há valor retornado.

Exemplos

Exemplo #1 SplFileObject::next() example

<?php
// Read through file line by line
$file = new SplFileObject("misc.txt");
while (!
$file->eof()) {
    echo 
$file->current();
    
$file->next();
}
?>

Veja Também



SplFileObject::rewind

(PHP 5 >= 5.1.0, PHP 7)

SplFileObject::rewindRewind the file to the first line

Descrição

public SplFileObject::rewind ( ) : void

Rewinds the file back to the first line.

Parâmetros

Esta função não possui parâmetros.

Valor Retornado

Não há valor retornado.

Erros

Throws a if cannot be rewound.

Exemplos

Exemplo #1 SplFileObject::rewind() example

<?php
$file 
= new SplFileObject("misc.txt");

// Loop over whole file
foreach ($file as $line) { }

// Rewind to first line
$file->rewind();

// Output first line
echo $file->current();
?>

Veja Também



SplFileObject::seek

(PHP 5 >= 5.1.0, PHP 7)

SplFileObject::seekSeek to specified line

Descrição

public SplFileObject::seek ( int $line_pos ) : void

Seek to specified line in the file.

Parâmetros

line_pos

The zero-based line number to seek to.

Valor Retornado

Não há valor retornado.

Erros

Throws a if the line_pos is negative.

Exemplos

Exemplo #1 SplFileObject::seek() example

This example outputs the third line of the script which is found at position 2.

<?php
$file 
= new SplFileObject(__FILE__);
$file->seek(2);
echo 
$file->current();
?>

O exemplo acima irá imprimir algo similar à:

$file->seek(2);

Veja Também



SplFileObject::setCsvControl

(PHP 5 >= 5.2.0, PHP 7)

SplFileObject::setCsvControlSet the delimiter, enclosure and escape character for CSV

Descrição

public SplFileObject::setCsvControl ([ string $delimiter = "," [, string $enclosure = "\"" [, string $escape = "\\" ]]] ) : void

Sets the delimiter, enclosure and escape character for parsing CSV fields.

Parâmetros

delimiter

The field delimiter (one character only).

enclosure

The field enclosure character (one character only).

escape

The field escape character (at most one character). An empty string ("") disables the proprietary escape mechanism.

Valor Retornado

Não há valor retornado.

Changelog

Versão Descrição
7.4.0 The escape parameter now also accepts an empty string to disable the proprietary escape mechanism.

Exemplos

Exemplo #1 SplFileObject::setCsvControl() example

<?php
$file 
= new SplFileObject("data.csv");
$file->setFlags(SplFileObject::READ_CSV);
$file->setCsvControl('|');
foreach (
$file as $row) {
    list (
$fruit, $quantity) = $row;
    
// Do something with values
}
?>

Contents of data.csv

<?php
apples|20
bananas|14
cherries|87
?>

Veja Também



SplFileObject::setFlags

(PHP 5 >= 5.1.0, PHP 7)

SplFileObject::setFlagsSets flags for the SplFileObject

Descrição

public SplFileObject::setFlags ( int $flags ) : void

Sets the flags to be used by the .

Parâmetros

flags

Bit mask of the flags to set. See for the available flags.

Valor Retornado

Não há valor retornado.

Exemplos

Exemplo #1 SplFileObject::setFlags() example

<?php
$file 
= new SplFileObject("data.csv");
$file->setFlags(SplFileObject::READ_CSV);
foreach (
$file as $fields) {
    
var_dump($fields);
}
?>

Veja Também



SplFileObject::setMaxLineLen

(PHP 5 >= 5.1.0, PHP 7)

SplFileObject::setMaxLineLenSet maximum line length

Descrição

public SplFileObject::setMaxLineLen ( int $max_len ) : void

Sets the maximum length of a line to be read.

Parâmetros

max_len

The maximum length of a line.

Valor Retornado

Não há valor retornado.

Erros

Throws when max_len is less than zero.

Exemplos

Exemplo #1 SplFileObject::setMaxLineLen() example

<?php
$file 
= new SplFileObject("lipsum.txt");
$file->setMaxLineLen(20);
foreach (
$file as $line) {
    echo 
$line . "\n";
}
?>

Contents of lipsum.txt

Lorem ipsum dolor sit amet, consectetur adipiscing elit.
Duis nec sapien felis, ac sodales nisl.
Nulla vitae magna vitae purus aliquet consequat.

O exemplo acima irá imprimir algo similar à:

Lorem ipsum dolor s
it amet, consectetu
r adipiscing elit.

Duis nec sapien fel
is, ac sodales nisl
.

Nulla vitae magna v
itae purus aliquet
consequat.

Veja Também



SplFileObject::__toString

(PHP 5 >= 5.1.0, PHP 7)

SplFileObject::__toStringAlias of

Descrição

Este método é um apelido para: .

Changelog

Versão Descrição
7.2.19, 7.3.6 Changed from an alias of to an alias of .


SplFileObject::valid

(PHP 5 >= 5.1.0, PHP 7)

SplFileObject::validNot at EOF

Descrição

public SplFileObject::valid ( ) : bool

Check whether EOF has been reached.

Parâmetros

Esta função não possui parâmetros.

Valor Retornado

Returns TRUE if not reached EOF, FALSE otherwise.

Exemplos

Exemplo #1 SplFileObject::valid() example

<?php
// Loop over a file, line by line
$file = new SplFileObject("file.txt");
while (
$file->valid()) {
    echo 
$file->fgets();
}
?>

Veja Também


Índice