PHP Read File Line by Line – fgets() Function

PHP fgets() function is used for reading single line from file This function takes two arguments as described below.
1. File specifies filename to read content 2. Length Optional parameter, specifies number of bytes to read from file.

Syntax

PHP fgets() function uses following syntax.
  fgets(file, length) 

Example – Read Single Line

Below is the two examples of reading single line from file using php script.
First example will read first 20 bytes from file.
<?php   $fn = fopen("myfile.txt","r");   $result = fgets($fn, 20);   echo $result;   fclose($fn); ?> 
Use this example to read complete first line content from file.
<?php   $fn = fopen("myfile.txt","r");   $result = fgets($fn);   echo $result;   fclose($fn); ?> 

Example – Read All Lines

Use this example to read all lines from files one by one using for loop. Use php feof() function to find end of file.
<?php   $fn = fopen("myfile.txt","r");      while(! feof($file))  {  $result = fgets($fn);  echo $result;   }    fclose($fn); ?> 

Thanks for Visit Here

Comments