Home > Article > Backend Development > How to use php fgets function
php The fgets function is used to read a line from the file pointer. Its syntax is fgets(file,length). The parameter file is required and specifies the file to be read.
#How to use php fgets function?
Definition and usage
fgets() function reads a line from the file pointer.
Syntax
fgets(file,length)
Parameters
file Required. Specifies the file to be read.
length Optional. Specifies the number of bytes to read. The default is 1024 bytes.
Description
Reads a line from the file pointed to by file and returns a string with a length of at most length - 1 bytes. Stops on encountering a newline character (included in the return value), EOF, or after length - 1 bytes have been read (whichever occurs first). If length is not specified, it defaults to 1K, or 1024 bytes.
If it fails, return false.
Tips and Notes
Note: The length parameter is optional as of PHP 4.2.0, and if omitted, the length of the line is assumed to be 1024 bytes. 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 8 KB, 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 don't.
Note: If you encounter that PHP cannot recognize the line ending characters of Macintosh files when reading the file, you can activate the auto_detect_line_endings runtime configuration option.
Example 1
<?php $file = fopen("test.txt","r"); echo fgets($file); fclose($file); ?>
Output similar to:
Hello, this is a test file.
Example 2
<?php $file = fopen("test.txt","r"); while(! feof($file)) { echo fgets($file). "<br />"; } fclose($file); ?>
Output similar to:
Hello, this is a test file. There are three lines here. This is the last line.
The above is the detailed content of How to use php fgets function. For more information, please follow other related articles on the PHP Chinese website!