Home > Article > Backend Development > PHP uses fgets() function to read file content examples in detail
php fgets() Function is used to read a line from the file pointer. This function can be combined with the feof function to read the file content. This article Let me share with you a simple example (demo) of using fgets() in PHP to read/obtain file content. Friends in need can refer to it.
First introduce the syntax of php fgets() function
fgets(file,length)
Detailed explanation of parameters
file Required. Specifies the file to be read.
length Optional. Specifies the number of bytes to read. The default is 1024 bytes.
Description
Read a line from the file pointed to by file and return a string with a length of at most length - 1 byte. 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.
If it fails, return false.
The following introduces the principle of PHP using the fgets() function to read files.
The fgets() function is used to read a line in the file. Therefore, we can always call the fgets() function to read the entire content of the file, and we can use the feof function to determine whether the last line of the file has been reached. , if the last line is reached, stop calling the fgets() function.
The specific example of the fgets() function reading the file is as follows:
Suppose we have a file data.txt with the following content:
a@example.com|Alice b@example.org|Bill c@example.com|Charlie c@example.com|China c@example.com|Phpcn
We use fgets() The function reads the contents of the file. The code is as follows:
<?php $fh = fopen('data.txt','rb'); if (! $fh) { print "Error opening people.txt: $php_errormsg"; } else { for ($line = fgets($fh); ! feof($fh); $line = fgets($fh)) { if ($line === false) { print "Error reading line: $php_errormsg"; } else { echo $line."<br/>"; } } if (! fclose($fh)) { print "Error closing people.txt: $php_errormsg"; } } ?>
First use the fopen function to open the file. The fopen function will return a file pointer, which will be used by the fgets function. Then use the fgets function to read a line in the file. Before reading, you must determine whether the last line has been reached. If the last line is reached, stop reading.
The above is the detailed content of PHP uses fgets() function to read file content examples in detail. For more information, please follow other related articles on the PHP Chinese website!