PHP fgets () function is used to read a row from the file pointer, the function can be combined with the feof function to read the contents of the file, this article to share with you PHP use Fgets () read/Get the file content of a simple example (demo), the need for friends can refer to.
First introduce the syntax of the PHP fgets () function
Fgets (File,length)
Detailed parameters
File required. Specifies the file to be read.
Length is optional. Specifies the number of bytes to read. The default is 1024 bytes.
Description
Reads a row from the file pointed to by the files and returns a string of up to length-1 bytes in length. Stop after encountering a newline character (included in the return value), EOF, or having read the length-1 byte (to see the case first). If length is not specified, the default is 1 K, or 1024 bytes.
If it fails, it returns false.
Here's how PHP uses the Fgets () function to read a file.
The fgets () function is used to read a line in a file, so we can always call the fgets () function to read the entire contents of the file, and you can use the Feof function to determine if the last line of the file has been reached and stop calling the Fgets () function if the last line is reached.
The fgets () function reads the file in the following instance:
Suppose we have a file data.txt, the contents of which are as follows:
A@example.com|alice B@example.org|bill C@example.com|charlie C@example.com|china C@EXAMPLE.COM|PHPCN
We use the fgets () function to read the contents of the file, with the following code:
<?PHP$FH = fopen (' data.txt ', ' RB '), if (! $fh) { print "Error opening people.txt: $php _errormsg";} else {for ($l ine = 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"; }}? >
Using the Fopen function to first open the file, the Fopen function returns a file pointer that will be used by the fgets function. Then use the Fgets function to read a row in the file, before reading to determine whether the last line has been reached, if the last line is reached, stop reading.