|
|
 |
fgets (PHP 3, PHP 4, PHP 5) fgets -- Obtiene una lÃnea desde el apuntador de
archivo Descripciónstring fgets ( resource gestor [, int longitud] )
Devuelve una cadena de hasta longitud - 1
bytes leÃdos desde el archivo apuntado por
gestor. La lectura termina cuando se han
leÃdo longitud - 1 bytes, se
alcanza un salto de lÃnea (el cual se incluye en el valor
devuelto), o en EOF (lo que ocurra primero). Si no se especifica
una longitud, el valor predeterminado es de 1k, o 1024 bytes.
Si ocurre un error, devuelve FALSE.
Errores comunes:
Aquellos acostumbrados a la semántice de
fgets() en 'C', debe notar la diferencia en el
modo en que EOF es devuelto.
El puntero de fichero debe de ser
valido y debe de apuntar a un fichero abierto con exito por
fopen() o fsockopen().
A continuación se presenta un ejemplo simple:
Ejemplo 1. Lectura de un archivo lÃnea a lÃnea |
<?php
$gestor = @fopen("/tmp/archivo_entrada.txt", "r");
if ($gestor) {
while (!feof($gestor)) {
$bufer = fgets($gestor, 4096);
echo $bufer;
}
fclose ($gestor);
}
?>
|
|
Nota:
El parámetro longitud se hizo
opcional en PHP 4.2.0, si se omite, se asume 1024 como la
longitud de lÃnea. A partir de PHP 4.3, al omitir
longitud, la lectura de la secuencia
continuará hasta que se alcance el final de la
lÃnea. Si la mayorÃa de lÃneas en el
archivo superan los 8KB, es más eficiente en
términos de recursos espicificar la longitud
máxima de lÃnea en su script.
Nota:
Esta función es segura con material binario desde PHP
4.3. Las versiones anteriores no contaban con ésta
caracterÃstica.
Nota: Si sufre problemas con
PHP no reconociendo los finales de lÃnea
cuando lee archivos creados en un Macintosh (o leyendo archivos sobre
uno), puede probar activando la opción de configuración
auto_detect_line_endings.
Vea también fgetss()
fread(), fgetc(),
stream_get_line(), fopen(),
popen(), fsockopen(), y
stream_set_timeout().
d at foo.com
13-Aug-2006 01:03
For sockets, If you dont want fgets, fgetc etc... to block if theres no data there. set socket_set_blocking(handle,false); and socket_set_blocking(handle,true); to set it back again.
svayn at yahoo dot com
14-Jul-2006 02:21
fgets is SLOW for scanning through large files. If you don't have PHP 5, use fscanf($file, "%s\n") instead.
sam dot bryan at montal dot com
23-May-2006 02:09
An easy way to authenticate Windows Domain users from scripts running on a non-Windows or non-Domain box - pass the submitted username and password to an IMAP service on a Windows machine.
<?php
$server = 'imapserver';
$user = 'user';
$pass = 'pass';
if (authIMAP($user, $pass, $server)) {
echo "yay";
} else {
echo "nay";
}
function authIMAP($user, $pass, $server) {
$connection = fsockopen($server, 143, $errno, $errstr, 30);
if(!$connection) return false;
$output = fgets($connection, 128); fputs($connection, "1 login $user $pass\r\n");
$output = fgets($connection, 128);
fputs($connection, "2 logout\r\n");
fclose($connection);
if (substr($output, 0, 4) == '1 OK') return true;
return false;
}
?>
24-Mar-2006 09:36
Macintosh line endings mentioned in docs refer to Mac OS Classic. You don't need this setting for interoperability with unixish OS X.
tavernadelleidee[italy]
09-Mar-2006 03:44
I think that the quickest way of read a (long) file with the rows in reverse order is
<?php
$myfile = 'myfile.txt';
$command = "tac $myfile > /tmp/myfilereversed.txt";
passthru($command);
$ic = 0;
$ic_max = 100; $handle = fopen("/tmp/myfilereversed.txt", "r");
while (!feof($handle) && ++$ic<=$ic_max) {
$buffer = fgets($handle, 4096);
echo $buffer."<br>";
}
fclose($handle);
?>
It echos the rows while it is reading the file so it is good for long files like logs.
Borgonovo
ecvej
04-Jan-2006 01:20
I would have expected the same behaviour from these bits of code:-
<?php
while (!feof($fp)) {
echo fgets($fp);
}
while ($line=fgets($fp)) {
echo $line;
}
stream_set_timeout($fp, 180);
while ($line=fgets($fp)) {
echo $line;
}
?>
hackajar <matt> yahoo <trot> com
05-Dec-2005 12:17
When working with VERY large files, php tends to fall over sideways and die.
Here is a neat way to pull chunks out of a file very fast and won't stop in mid line, but rater at end of last known line. It pulled a 30+ million line 900meg file through in ~ 24 seconds.
NOTE:
$buf just hold current chunk of data to work with. If you try "$buf .=" (note 'dot' in from of '=') to append $buff, script will come to grinding crawl around 100megs of data, so work with current data then move on!
//File to be opened
$file = "huge.file";
//Open file (DON'T USE a+ pointer will be wrong!)
$fp = fopen($file, 'r');
//Read 16meg chunks
$read = 16777216;
//\n Marker
$part = 0;
while(!feof($fp)) {
$rbuf = fread($fp, $read);
for($i=$read;$i > 0 || $n == chr(10);$i--) {
$n=substr($rbuf, $i, 1);
if($n == chr(10))break;
//If we are at the end of the file, just grab the rest and stop loop
elseif(feof($fp)) {
$i = $read;
$buf = substr($rbuf, 0, $i+1);
break;
}
}
//This is the buffer we want to do stuff with, maybe thow to a function?
$buf = substr($rbuf, 0, $i+1);
//Point marker back to last \n point
$part = ftell($fp)-($read-($i+1));
fseek($fp, $part);
}
fclose($fp);
kpeters AT-AT monolithss DEE OH TEE com
01-Dec-2005 05:51
It appears that fgets() will return FALSE on EOF (before feof has a chance to read it), so this code will throw an exception:
while (!feof($fh)) {
$line = fgets($fh);
if ($line === false) {
throw new Exception("File read error");
}
}
dandrews OVER AT 3dohio DOT com
07-Jan-2005 11:11
Saku's example may also be used like this:
<?php
@ $pointer = fopen("$DOCUMENT_ROOT/foo.txt", "r"); if ($pointer) {
while (!feof($pointer)) {
$preTEXT = fgets($pointer, 999);
$ATEXT[$I] = $preTEXT; $I++;
}
fclose($pointer);
}
?>
angelo [at] mandato <dot> com
19-Nov-2004 06:43
Sometimes the strings you want to read from a file are not separated by an end of line character. the C style getline() function solves this. Here is my version:
<?php
function getline( $fp, $delim )
{
$result = "";
while( !feof( $fp ) )
{
$tmp = fgetc( $fp );
if( $tmp == $delim )
return $result;
$result .= $tmp;
}
return $result;
}
$fp = fopen("/path/to/file.ext", 'r');
while( !feof($fp) )
{
$str = getline($fp, '|');
}
fclose($fp);
?>
lelkesa
04-Nov-2004 02:54
Note that - afaik - fgets reads a line until it reaches a line feed (\\n). Carriage returns (\\r) aren't processed as line endings.
However, nl2br insterts a <br /> tag before carriage returns as well.
This is useful (but not nice - I must admit) when you want to store a more lines in one.
<?php
function write_lines($text) {
$file = fopen('data.txt', 'a');
fwrite($file, str_replace("\n", ' ', $text)."\n");
fclose($file);
}
function read_all() {
$file = fopen('data.txt', 'r');
while (!feof($file)) {
$line = fgets($file);
echo '<u>Section</u><p>nl2br'.($line).'</p>';
}
fclose($file);
}
?>
Try it.
05-Sep-2004 03:05
If you need to simulate an un-buffered fgets so that stdin doesnt hang there waiting for some input (i.e. it reads only if there is data available) use this :
<?php
function fgets_u($pStdn) {
$pArr = array($pStdn);
if (false === ($num_changed_streams = stream_select($pArr, $write = NULL, $except = NULL, 0))) {
print("\$ 001 Socket Error : UNABLE TO WATCH STDIN.\n");
return FALSE;
} elseif ($num_changed_streams > 0) {
return trim(fgets($pStdn, 1024));
}
}
?>
rstefanowski at wi dot ps dot pl
12-Aug-2004 09:03
Take note that fgets() reads 'whole lines'. This means that if a file pointer is in the middle of the line (eg. after fscanf()), fgets() will read the following line, not the remaining part of the currnet line. You could expect it would read until the end of the current line, but it doesn't. It skips to the next full line.
timr
16-Jun-2004 07:13
If you need to read an entire file into a string, use file_get_contents(). fgets() is most useful when you need to process the lines of a file separately.
Saku
04-Jun-2004 05:47
As a beginner I would have liked to see "how to read a file into a string for use later and not only how to directly echo the fgets() result. This is what I derived:
<?php
@ $pointer = fopen("$DOCUMENT_ROOT/foo.txt", "r"); if ($pointer) {
while (!feof($pointer)) {
$preTEXT = fgets($pointer, 999);
$TEXT = $TEXT . $preTEXT;
}
fclose($pointer);
}
?>
flame
21-May-2004 08:44
fread is binary safe, if you are stuck with a pre 4.3 version of PHP.
Pete
22-Feb-2004 04:35
If you have troubles reading binary data with versions <= 4.3.2 then upgrade to 4.3.3
The binary safe implementation seems to have had bugs which were fixed in 4.3.3
| |
| | Citas célebres | El hombre que es poeta a los veinte años no es poeta: es hombre. Si es poeta después de los veinte años, entonces es poeta. Charles Péguy Escritor francés (1873-1914) | | Citas en tu mail | | ©Contenidos Gratis |
| Chiste de... Parejas | | Confusión en la alcoba | - Estaba con ella cuando llamaron a la puerta. Creí que era el marido. Salté por la ventana a la escalera de incendios, pero me confundí.
- No era el marido...
- No. No había escalera. | | Chistes en tu mail | | ©ContenidosGratis |
| Inicio | Acción | Estrategia | Palabras | Puzzles | Solitarios | Foro Trucos |  | Cake Mania Jugadores: 6835 Categoría del juego: Acción Objetivo del juego: Ayuda a Jill a recuperar la pastelería de su abuela llevando su propia pastelería; consigue clientes y gana dinero. |
|  | Rainbow Web Jugadores: 2199 Categoría del juego: Puzzles Objetivo del juego: Rompe un pegajoso hechizo y salva un reino de fantasía en Rainbow Web. Tendrás toneladas de diversión mientras juegas a este mágico desafío para la mente. |
|  | Mahjongg Fortuna Jugadores: 12462 Categoría del juego: Solitarios Objetivo del juego: Velocidad y habilidad mental son las armas más importantes en esta versión de un antiguo juego asiático. Despeja el tablero lo antes posible haciendo clic en las fichas iguales y gánate la fama eterna de la puntuación más alta. |
|  | Chainz 2 Jugadores: 6955 Categoría del juego: Puzzles Objetivo del juego: Entra en el mundo de las combinaciones con Chainz 2: Relinked, emocionante secuela del exitazo del año pasado, Chainz. Gira eslabones y crea combinaciones de 3 ó más. |
|  | Delicious Jugadores: 4405 Categoría del juego: Acción Objetivo del juego: ¿Eres un as de la multitarea? ¿Quieres que tus clientes estén contentos? ¡Pues Delicious es tu juego! Sacia el apetito de los clientes y tenlos contentos; ¡no te arriesgues! |
|  | Bookworm Jugadores: 4568 Categoría del juego: Palabras Objetivo del juego: Junta las letras para formar palabras. ¡Las palabras más largas valen más puntos! |
|  | Zuma Jugadores: 4976 Categoría del juego: Acción Objetivo del juego: Controla el ídolo de la rana de piedra de los antiguos Zuma en este intrigante enigma de acción. ¡Dispara bolas para formar conjuntos de tres, pero si dejas que lleguen a la calavera dorada morirás! |
|  | Jewel of Atlantis Jugadores: 3798 Categoría del juego: Puzzles Objetivo del juego: Descubre la ciudad hundida de la Atlántida y busca valiosos tesoros. Viaja más allá de las profundidades del mar y vive trepidantes aventuras en Jewel of Atlantis. |
|  | Jewel Quest Jugadores: 3727 Categoría del juego: Puzzles Objetivo del juego: Convierte la arena de la antigua selva en oro tan rápido como puedas juntando grupos de 3 elementos. ¡Los grupos más grandes valen más puntos! |
|  | Bejeweled 2 Jugadores: 3659 Categoría del juego: Puzzles Objetivo del juego: Con cuatro modos de juego únicos y fascinantes, nuevas piezas de juego explosivas e imponentes fondos planetarios, Bejeweled 2 es mucho más adictivo que nunca. |
|
|