English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Basic PHP Tutorial

Advanced PHP Tutorial

PHP & MySQL

PHP Reference Manual

PHP fgets() Function Usage and Example

PHP Filesystem Reference Manual

The fgets() function can return a line from an open file. This function stops at the specified length of a new line or EOF, whichever comes first, and returns false on failure.

Syntax

string fgets ( resource $handle [, int $length ] )

Reads a line from the file pointed to by handle and returns a string of up to length bytes - 1 bytes string. It stops at the newline character (including in the returned value), EOF, or after reading length - 1 bytes and stop (depending on which one is encountered first). If length is not specified, the default is 1K, or 1024 bytes.
Note: From PHP 4.3 At the beginning, if length is ignored, the line length is assumed to be 1024, it will continue to read data from the stream until the end of the line. If most lines in the file are greater than 8If most lines in the file are greater than KB, it is more effective to specify the maximum line length in the script in terms of resource usage.

Example1

<?php
   $file = fopen("/PhpProject/sample.txt", "r");
   echo fgets($file);
   fclose($file);
?>

Output Result

oldtoolbag.com

Example2

<?php
   $file = fopen("/PhpProject/sample.txt", "r");
 
   while(! feof($file)) {
      echo fgets($file) . '\n';
   }
 
   fclose($file);
?>

Output Result

oldtoolbag.com
www.oldtoolbag.com

PHP Filesystem Reference Manual