★ wanayoo — archive 1999 http://uk.php.net/manual/sv/function.fgets.phpNouvelle recherche | Portail wanayoo
PHP  
downloads | documentation | faq | getting help | mailing lists | reporting bugs | php.net sites | links | my php.net 
search for in the  
<fgetcsvfgetss>
view the version of this page
Last updated: Sat, 17 Jul 2004

fgets

(PHP 3, PHP 4 , PHP 5)

fgets -- Gets line from file pointer

Description

string 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:

Exempel 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);
?>

Not: 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.

Not: This function is binary safe as of PHP 4.3. Earlier versions were not binary safe.

Not: Om du har problem med att PHP inte känner igen radslut vid hantering av filer på en Macintosh (antingen om de är skrivna på en Mac eller skapade på en) kan det vara idé att slå på direktivet auto_detect_line_endings i din konfigurationsfil.

See also fread(), fgetc(), stream_get_line(), fopen(), popen(), fsockopen(), and stream_set_timeout().



add a note add a note User Contributed Notes
fgets
dandrews OVER AT 3dohio DOT com
07-Jan-2005 07:11
Saku's example may also be used like this:

<?php
 
@ $pointer = fopen("$DOCUMENT_ROOT/foo.txt", "r"); // the @ suppresses errors so you have to test the pointer for existence
  
if ($pointer) {
     while (!
feof($pointer)) {
        
$preTEXT = fgets($pointer, 999);
        
// $TEXT .= $preTEXT;  this is better for a string
      
$ATEXT[$I] = $preTEXT// maybe better as an array
      
$I++;
     }
    
fclose($pointer);
   }
?>
kevinh at actofmind dot com
06-Dec-2004 04: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 04: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 02: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;
}

// Example:
$fp = fopen("/path/to/file.ext", 'r');
while( !
feof($fp) )
{
  
$str = getline($fp, '|');
  
// Do something with $str
}
fclose($fp);
?>
lelkesa
04-Nov-2004 10: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 11: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 05: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
17-Jun-2004 03: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
05-Jun-2004 01: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"); // the @ suppresses errors so you have to test the pointer for existence
  
if ($pointer) {
     while (!
feof($pointer)) {
        
$preTEXT = fgets($pointer, 999);
        
$TEXT = $TEXT . $preTEXT;
     }
    
fclose($pointer);
   }
?>
flame
22-May-2004 04:44
fread is binary safe, if you are stuck with a pre 4.3 version of PHP.
Pete
23-Feb-2004 12: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

<fgetcsvfgetss>
 Last updated: Sat, 17 Jul 2004
show source | credits | sitemap | contact | advertising | mirror sites 
Copyright © 2001-2005 The PHP Group
All rights reserved.
This mirror generously provided by: Kewlio.net Limited
Last updated: Thu Feb 10 00:14:32 2005 GMT