The SplFileObject class (PHP 5 >= 5.1.0, PHP 7)
The SplFileObject class offers an object oriented interface for a file.
Sinopse da classe
$filename
[, string $open_mode
= "r" [, bool $use_include_path
= FALSE
[, resource $context
]]] )$delimiter
= "," [, string $enclosure
= "\"" [, string $escape
= "\\" ]]] ) : array$fields
[, string $delimiter
= "," [, string $enclosure
= '"' [, string $escape
= "\\" ]]] ) : int|false$delimiter
= "," [, string $enclosure
= "\"" [, string $escape
= "\\" ]]] ) : void$open_mode
= "r" [, bool $use_include_path
= FALSE
[, resource $context
= NULL
]]] ) : SplFileObjectConstantes 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::__construct — Construct a new file object
Descrição
$filename
[, string $open_mode
= "r" [, bool $use_include_path
= FALSE
[, resource $context
]]] )Construct a new file object.
Parâmetros
filename
-
The file to read.
DicaUma URL pode ser utilizada como um nome de arquivo se fopen wrappers estiver ativo. Veja fopen() para mais detalhes em como especificar URLs como nome de arquivo. Veja também the Protocolos e Wrappers suportados 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 fopen() for a list of allowed modes.
use_include_path
-
Whether to search in the include_path for
filename
. context
-
A valid context resource created with stream_context_create().
Valor Retornado
Não há valor retornado.
Erros
Throws a RuntimeException if the filename
cannot be opened.
Throws a LogicException 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
- SplFileInfo::openFile() - Gets an SplFileObject object for the file
- fopen() - Abre um arquivo ou URL
SplFileObject::current
(PHP 5 >= 5.1.0, PHP 7)
SplFileObject::current — Retrieve current line of file
Descrição
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::key() - Get line number
- SplFileObject::seek() - Seek to specified line
- SplFileObject::next() - Read next line
- SplFileObject::rewind() - Rewind the file to the first line
- SplFileObject::valid() - Not at EOF
SplFileObject::eof
(PHP 5 >= 5.1.0, PHP 7)
SplFileObject::eof — Reached end of file
Descrição
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::valid() - Not at EOF
- feof() - Testa pelo fim-de-arquivo (eof) em um ponteiro de arquivo
SplFileObject::fflush
(PHP 5 >= 5.1.0, PHP 7)
SplFileObject::fflush — Flushes the output to the file
Descrição
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::fwrite() - Write to file
SplFileObject::fgetc
(PHP 5 >= 5.1.0, PHP 7)
SplFileObject::fgetc — Gets character from file
Descrição
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.
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 Booleanos para maiores informações. Utilize o operador === 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::fgets() - Gets line from file
SplFileObject::fgetcsv
(PHP 5 >= 5.1.0, PHP 7)
SplFileObject::fgetcsv — Gets line from file and parse as CSV fields
Descrição
$delimiter
= "," [, string $enclosure
= "\"" [, string $escape
= "\\" ]]] ) : arrayGets 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 SplFileObject::setCsvControl().
enclosure
-
The field enclosure character (one character only). Defaults as a double quotation mark or the value set using SplFileObject::setCsvControl().
escape
-
The escape character (at most one character). Defaults as a backslash (
\
) or the value set using SplFileObject::setCsvControl(). An empty string (""
) disables the proprietary escape mechanism.Nota: Usually an
enclosure
character is escpaped inside a field by doubling it; however, theescape
character can be used as an alternative. So for the default parameter values""
and\"
have the same meaning. Other than allowing to escape theenclosure
character theescape
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 usingSplFileObject::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::setCsvControl() - Set the delimiter, enclosure and escape character for CSV
- SplFileObject::setFlags() - Sets flags for the SplFileObject
- SplFileObject::READ_CSV
- SplFileObject::current() - Retrieve current line of file
SplFileObject::fgets
(PHP 5 >= 5.1.0, PHP 7)
SplFileObject::fgets — Gets line from file
Descrição
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 RuntimeException 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
- fgets() - Lê uma linha de um ponteiro de arquivo
- SplFileObject::fgetss() - Gets line from file and strip HTML tags
- SplFileObject::fgetc() - Gets character from file
- SplFileObject::current() - Retrieve current line of file
SplFileObject::fgetss
(PHP 5 >= 5.1.0, PHP 7)
SplFileObject::fgetss — Gets line from file and strip HTML tags
This function has been DEPRECATED as of PHP 7.3.0. Relying on this function is highly discouraged.
Descrição
$allowable_tags
] ) : stringIdentical to SplFileObject::fgets(), 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 strip_tags() on the return value of SplFileObject::fgets().
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
- fgetss() - Ler uma linha de um ponteiro de arquivo e retira as tags HTML
- SplFileObject::fgets() - Gets line from file
- SplFileObject::fgetc() - Gets character from file
- SplFileObject::current() - Retrieve current line of file
- The string.strip_tags filter
SplFileObject::flock
(PHP 5 >= 5.1.0, PHP 7)
SplFileObject::flock — Portable file locking
Descrição
$operation
[, int &$wouldblock
] ) : boolLocks or unlocks the file in the same portable way as flock().
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 flock() 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
- flock() - Monitor de travamento de arquivos portátil
SplFileObject::fpassthru
(PHP 5 >= 5.1.0, PHP 7)
SplFileObject::fpassthru — Output all remaining data on a file pointer
Descrição
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 SplFileObject::rewind() 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
- fpassthru() - Imprime todo os dados restantes de um ponteiro de arquivo
SplFileObject::fputcsv
(PHP 5 >= 5.4.0, PHP 7)
SplFileObject::fputcsv — Write a field array as a CSV line
Descrição
$fields
[, string $delimiter
= "," [, string $enclosure
= '"' [, string $escape
= "\\" ]]] ) : int|falseWrites 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 anescape_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
- fputcsv() - Formata a linha como CSV e a escreve em um ponteiro de arquivo
- SplFileObject::fgetcsv() - Gets line from file and parse as CSV fields
SplFileObject::fread
(PHP 5 >= 5.5.11, PHP 7)
SplFileObject::fread — Read from file
Descrição
$length
) : string|falseReads 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 SplFileObject::ftell() to find the current position of the pointer and SplFileObject::rewind() (or SplFileObject::fseek()) to rewind the pointer position.
Veja Também
- fread() - Leitura binary-safe de arquivo
SplFileObject::fscanf
(PHP 5 >= 5.1.0, PHP 7)
SplFileObject::fscanf — Parses input from file according to a format
Descrição
Reads a line from the file and interprets it according to the specified format
, which is described in the documentation for sprintf().
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
andF
specifiers: this is the number of digits to be printed after the decimal point (by default, this is 6). - For
g
andG
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 usesE
andf
.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). AvisoThe
c
type specifier ignores padding and widthAvisoAttempting 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
- For
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
SplFileObject::fseek
(PHP 5 >= 5.1.0, PHP 7)
SplFileObject::fseek — Seek to a position
Descrição
$offset
[, int $whence
= SEEK_SET ] ) : intSeek 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 tooffset
bytes.SEEK_CUR
- Set position to current location plusoffset
.SEEK_END
- Set position to end-of-file plusoffset
.
If
whence
is not specified, it is assumed to beSEEK_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
- fseek() - Procura (seeks) em um ponteiro de arquivo
SplFileObject::fstat
(PHP 5 >= 5.1.0, PHP 7)
SplFileObject::fstat — Gets information about the file
Descrição
Gathers the statistics of the file. Behaves identically to fstat().
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 stat() 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 )
SplFileObject::ftell
(PHP 5 >= 5.1.0, PHP 7)
SplFileObject::ftell — Return current file position
Descrição
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
- ftell() - Retorna a posição de leitura/gravação do ponteiro do arquivo
SplFileObject::ftruncate
(PHP 5 >= 5.1.0, PHP 7)
SplFileObject::ftruncate — Truncates the file to a given length
Descrição
$size
) : boolTruncates 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
- ftruncate() - Reduz um arquivo a um tamanho especificado
SplFileObject::fwrite
(PHP 5 >= 5.1.0, PHP 7)
SplFileObject::fwrite — Write to file
Descrição
$str
[, int $length
] ) : intWrites 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 afterlength
bytes have been written or the end ofstring
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
- fwrite() - Escrita binary-safe em arquivos
SplFileObject::getChildren
(PHP 5 >= 5.1.0, PHP 7)
SplFileObject::getChildren — No purpose
Descrição
An SplFileObject 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
- RecursiveIterator::getChildren() - Returns an iterator for the current entry
SplFileObject::getCsvControl
(PHP 5 >= 5.2.0, PHP 7)
SplFileObject::getCsvControl — Get the delimiter, enclosure and escape character for CSV
Descrição
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::setCsvControl() - Set the delimiter, enclosure and escape character for CSV
- SplFileObject::fgetcsv() - Gets line from file and parse as CSV fields
SplFileObject::getCurrentLine
(PHP 5 >= 5.1.2, PHP 7)
SplFileObject::getCurrentLine — Alias of SplFileObject::fgets()
Descrição
Este método é um apelido para: SplFileObject::fgets().
SplFileObject::getFlags
(PHP 5 >= 5.1.0, PHP 7)
SplFileObject::getFlags — Gets flags for the SplFileObject
Descrição
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::setFlags() - Sets flags for the SplFileObject
SplFileObject::getMaxLineLen
(PHP 5 >= 5.1.0, PHP 7)
SplFileObject::getMaxLineLen — Get maximum line length
Descrição
Gets the maximum line length as set by SplFileObject::setMaxLineLen().
Parâmetros
Esta função não possui parâmetros.
Valor Retornado
Returns the maximum line length if one has been set with SplFileObject::setMaxLineLen(), 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::setMaxLineLen() - Set maximum line length
SplFileObject::hasChildren
(PHP 5 >= 5.1.2, PHP 7)
SplFileObject::hasChildren — SplFileObject does not have children
Descrição
An SplFileObject 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
- RecursiveIterator::hasChildren() - Returns if an iterator can be created for the current entry
SplFileObject::key
(PHP 5 >= 5.1.0, PHP 7)
SplFileObject::key — Get line number
Descrição
Gets the current line number.
Nota:
This number may not reflect the actual line number in the file if SplFileObject::setMaxLineLen() 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 SplFileObject::setMaxLineLen()
<?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::current() - Retrieve current line of file
- SplFileObject::seek() - Seek to specified line
- SplFileObject::next() - Read next line
- SplFileObject::rewind() - Rewind the file to the first line
- SplFileObject::valid() - Not at EOF
SplFileObject::next
(PHP 5 >= 5.1.0, PHP 7)
SplFileObject::next — Read next line
Descrição
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::current() - Retrieve current line of file
- SplFileObject::key() - Get line number
- SplFileObject::seek() - Seek to specified line
- SplFileObject::rewind() - Rewind the file to the first line
- SplFileObject::valid() - Not at EOF
SplFileObject::rewind
(PHP 5 >= 5.1.0, PHP 7)
SplFileObject::rewind — Rewind the file to the first line
Descrição
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 RuntimeException 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::current() - Retrieve current line of file
- SplFileObject::key() - Get line number
- SplFileObject::seek() - Seek to specified line
- SplFileObject::next() - Read next line
- SplFileObject::valid() - Not at EOF
SplFileObject::seek
(PHP 5 >= 5.1.0, PHP 7)
SplFileObject::seek — Seek to specified line
Descrição
$line_pos
) : voidSeek 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 LogicException 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::current() - Retrieve current line of file
- SplFileObject::key() - Get line number
- SplFileObject::next() - Read next line
- SplFileObject::rewind() - Rewind the file to the first line
- SplFileObject::valid() - Not at EOF
SplFileObject::setCsvControl
(PHP 5 >= 5.2.0, PHP 7)
SplFileObject::setCsvControl — Set the delimiter, enclosure and escape character for CSV
Descrição
$delimiter
= "," [, string $enclosure
= "\"" [, string $escape
= "\\" ]]] ) : voidSets 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::getCsvControl() - Get the delimiter, enclosure and escape character for CSV
- SplFileObject::fgetcsv() - Gets line from file and parse as CSV fields
SplFileObject::setFlags
(PHP 5 >= 5.1.0, PHP 7)
SplFileObject::setFlags — Sets flags for the SplFileObject
Descrição
$flags
) : voidSets the flags to be used by the SplFileObject.
Parâmetros
flags
-
Bit mask of the flags to set. See SplFileObject constants 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::getFlags() - Gets flags for the SplFileObject
SplFileObject::setMaxLineLen
(PHP 5 >= 5.1.0, PHP 7)
SplFileObject::setMaxLineLen — Set maximum line length
Descrição
$max_len
) : voidSets 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 DomainException 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::getMaxLineLen() - Get maximum line length
SplFileObject::__toString
(PHP 5 >= 5.1.0, PHP 7)
SplFileObject::__toString — Alias of SplFileObject::fgets()
Descrição
Este método é um apelido para: SplFileObject::fgets().
Changelog
Versão | Descrição |
---|---|
7.2.19, 7.3.6 | Changed from an alias of SplFileObject::current() to an alias of SplFileObject::fgets(). |
SplFileObject::valid
(PHP 5 >= 5.1.0, PHP 7)
SplFileObject::valid — Not at EOF
Descrição
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
- SplFileObject::current() - Retrieve current line of file
- SplFileObject::key() - Get line number
- SplFileObject::seek() - Seek to specified line
- SplFileObject::next() - Read next line
- SplFileObject::rewind() - Rewind the file to the first line
Índice
- SplFileObject::__construct - Construct a new file object
- SplFileObject::current - Retrieve current line of file
- SplFileObject::eof - Reached end of file
- SplFileObject::fflush - Flushes the output to the file
- SplFileObject::fgetc - Gets character from file
- SplFileObject::fgetcsv - Gets line from file and parse as CSV fields
- SplFileObject::fgets - Gets line from file
- SplFileObject::fgetss - Gets line from file and strip HTML tags
- SplFileObject::flock - Portable file locking
- SplFileObject::fpassthru - Output all remaining data on a file pointer
- SplFileObject::fputcsv - Write a field array as a CSV line
- SplFileObject::fread - Read from file
- SplFileObject::fscanf - Parses input from file according to a format
- SplFileObject::fseek - Seek to a position
- SplFileObject::fstat - Gets information about the file
- SplFileObject::ftell - Return current file position
- SplFileObject::ftruncate - Truncates the file to a given length
- SplFileObject::fwrite - Write to file
- SplFileObject::getChildren - No purpose
- SplFileObject::getCsvControl - Get the delimiter, enclosure and escape character for CSV
- SplFileObject::getCurrentLine - Alias of SplFileObject::fgets
- SplFileObject::getFlags - Gets flags for the SplFileObject
- SplFileObject::getMaxLineLen - Get maximum line length
- SplFileObject::hasChildren - SplFileObject does not have children
- SplFileObject::key - Get line number
- SplFileObject::next - Read next line
- SplFileObject::rewind - Rewind the file to the first line
- SplFileObject::seek - Seek to specified line
- SplFileObject::setCsvControl - Set the delimiter, enclosure and escape character for CSV
- SplFileObject::setFlags - Sets flags for the SplFileObject
- SplFileObject::setMaxLineLen - Set maximum line length
- SplFileObject::__toString - Alias of SplFileObject::fgets
- SplFileObject::valid - Not at EOF