The fgets() functions is used to read a line from a file. Using this function we either read the entire line into a string or specify the number characters we like to read.

fgets ($handle, $length);

  • $handle - the file pointer
  • $length - number of bytes to read. If length is not specified it will read at the end of the line.

Reading entire line

<?php
$fh = fopen("myfile.txt", "r");

$line = fgets($fh);
echo $line;

fclose($fh);
?>

Reading number of bytes

<?php
$fh = fopen("myfile.txt", "r");

$str = fgets($fh, 64);
echo $str;

$line2 = fgets($fh, 64);
echo $str;

fclose($fh);
?>

Reading file line by line

<?php
$fh = fopen("myfile.txt", "r");

while(true)
{
$line = fgets($fh);
if($line == null)break;

echo $line;
}

fclose($fh);
?>

Reading entire file at once

<?php
$fh = fopen("myfile.txt", "r");

$file = file_get_contents("myfile.txt");
echo $file;
?>

Related Posts by Categories