|
|
 |
fgets (PHP 3, PHP 4, PHP 5) fgets -- Gets line from file pointer Descriptionstring fgets ( resource handle [, int length] )
Returns a string of up to length - 1 bytes read from
the file pointed to by handle. Reading ends when
length - 1 bytes have been read, on a newline (which is
included in the return value), or on EOF (whichever comes first). If no length
is specified, the length defaults to 1k, or 1024 bytes.
If an error occurs, returns FALSE.
Common Pitfalls:
People used to the 'C' semantics of fgets()
should note the difference in how EOF is returned.
The file pointer must be valid, and must point to
a file successfully opened by fopen() or
fsockopen().
A simple example follows:
Example 1. Reading a file line by line |
<?php
$handle = fopen("/tmp/inputfile.txt", "r");
while (!feof($handle)) {
$buffer = fgets($handle, 4096);
echo $buffer;
}
fclose($handle);
?>
|
|
Note:
The length parameter became optional in PHP
4.2.0, if omitted, it would assume 1024 as the line length.
As of PHP 4.3, omitting length will keep
reading from the stream until it reaches the end of the line.
If the majority of the lines in the file are all larger than 8KB,
it is more resource efficient for your script to specify the maximum
line length.
Note:
This function is binary safe as of PHP 4.3. Earlier versions
were not binary safe.
Note: If you are having problems
with PHP not recognizing the line endings when reading files either on or
created by a Macintosh computer, you might want to enable the
auto_detect_line_endings
run-time configuration option.
See also fread(),
fgetc(),
stream_get_line(),
fopen(),
popen(),
fsockopen(), and
stream_set_timeout().
User Contributed Notes
fgets
Jonathan Ray
19-May-2005 12:25
An even easier way is to leave out the "!= false", as it is redundant.
$fhandle = fopen("file_name","r");
while ($line = fgets($fhandle)) {
$line = trim($line);
echo $line;
echo "\n";
}
dcanas at intnet dot co dot cr
19-Apr-2005 06:15
An easier way to read a file and eliminate unwanted carriage returna, line feeds... and avoids the problem with reading an extra line.
$fhandle = fopen("file_name","r");
while ( ($line = fgets($fhandle)) != false ) {
$line = trim($line);
echo $line;
echo "\n";
}
Allen
20-Mar-2005 07:35
It seems to me that the main example for fgets() is misleading. This example, used as written, will process all the code in the "while" once for each line of the file, and once again after feof() becomes true after the fgets(). The "echo $buffer" statement gets executed even when $buffer has not been returned.
Upon investigation I found that $buffer is indeed set to false when the fgets() attempts to read at EOF. This would seem appropriate:
<?php
$handle = fopen("/tmp/inputfile.txt", "r");
while ($buffer = fgets($handle,4096)) {
echo $buffer;
}
fclose($handle);
?>
The original example could be coded as:
<?php
$handle = fopen("/tmp/inputfile.txt", "r");
while (!feof($handle)) {
$buffer = fgets($handle, 4096);
if (!feof($handle)) {
echo $buffer;
}
}
fclose($handle);
?>
dandrews OVER AT 3dohio DOT com
07-Jan-2005 01: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);
}
?>
kevinh at actofmind dot com
06-Dec-2004 10:47
Example 1 goes into an infinite loop if fopen() fails. In my mod_php context, this creates a near undiagnosable memory black hole. The memory consumption is so severe that it even prevents transmission of the PHP error messages. May I recommend instead:
<?php
$handle = fopen("/tmp/inputfile.txt", "r");
if($handle) {
while (!feof($handle)) {
$buffer = fgets($handle, 4096);
echo $buffer;
}
fclose($handle);
}
?>
29-Nov-2004 10:29
jim told how to read the last line, here is fastest way to read the first line:
<?php
function readfirstline($file){
$fp = @fopen($file, "r");
$firstline = fgets($fp);
fclose($fp);
return $firstline;
}
?>
angelo [at] mandato <dot> com
19-Nov-2004 08: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 04: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 05: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 11: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 09: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 07: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 10:44
fread is binary safe, if you are stuck with a pre 4.3 version of PHP.
Pete
22-Feb-2004 06: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
| |