The following code shows an Example of fgets() Function in PHP. When we need to read a line of a file, we can use this function. More information on this function is available in PHP Manual.

The fgets() function in PHP allow us to read a line in a file. The following PHP script opens a text file in read-mode. When we call this function, it returns the first line. Since initially the file pointer is pointing at the beginning of the file. In order to read the whole content line by line, first, we move the file pointer back to the beginning of the file using the fseek() function. After that, the while loop reads all lines till the end of the file is reached.

For the purpose of this example, we use the following text file.

TextFile.txy
TextFile.txy
<?php
  $myfile=fopen('TextFile.txt', 'r');
  //reading the first Line
  echo 'First Line in the file...<br>';
  echo fgets($myfile);
  //Reading the file line by line
  echo '<br>Reading the file line by line...<br>';
  fseek($myfile, 0);
  $counter=1;
  while(!feof($myfile))
  {
     echo '[',$counter,'] ',fgets($myfile),'<br>';
     $counter++;
  }
  echo '<br>Total Lines in the File: ',$counter-1;
  fclose($myfile);
?>

Output

Example of fgets() Function in PHP - Reading File Line By Line
Example of fgets() Function in PHP – Reading File Line By Line

Further Reading

Examples of Array Functions in PHP

Basic Programs in PHP

programmingempire

princites.com