PHP function fgets -- read a line of instructions from the file pointer
string fgets ( int handle [, int length] )
Reads a line from the file pointed to by handle and returns a string of length at most length - 1 bytes. Stops when a newline character (included in the return value), EOF, or length - 1 bytes has been read (whichever occurs first). If length is not specified, it defaults to 1K, or 1024 bytes.
Returns FALSE on error.
Common defects of PHP function fgets:
Those who are used to the syntax of fgets() in C language should notice how EOF is returned.
The file pointer must be valid and must point to a file successfully opened by fopen() or fsockopen().
The following is a simple example of the PHP function fgets: Example 1. Read a file line by line
<ol class="dp-xml"><li class="alt"><span><span class="tag"><</span><span> ?php </span></span></li><li><span>$</span><span class="attribute">handle</span><span> = </span><span class="attribute-value">fopen</span><span>("/tmp/<br />inputfile.txt", "r"); </span></li><li class="alt"><span>while (!feof($handle)) { </span></li><li><span>$</span><span class="attribute">buffer</span><span> = </span><span class="attribute-value">fgets</span><span>($fd, 4096); </span></li><li class="alt"><span>echo $buffer; </span></li><li><span>} </span></li><li class="alt"><span>fclose($handle); </span></li><li><span class="tag">?></span><span> </span></span></li></ol>
Note: The length parameter becomes optional from PHP 4.2.0, if ignored, then The row length is assumed to be 1024. Starting with PHP 4.3, omitting length will continue reading from the stream until the end of the line. If most of the lines in the file are larger than 8KB, specifying the maximum line length in the script is more efficient in utilizing resources.
Note: Starting from PHP 4.3, this function can be safely used in binary files. Earlier versions did not.
Note: If you encounter that the PHP function fgets cannot recognize the line ending characters of Macintosh files when reading files, you can activate the auto_detect_line_endings runtime configuration option.