fgets() function in PHP


The fgets() function returns a line from a file. It returns a string of up to length - 1 bytes read from the file pointed to by file_pointer.

Syntax

fgets (file_pointer, length);

Parameters

  • file_pointer − The file pointer must be valid, and must point to a file successfully opened by fopen() or fsockopen().

  • length − Reading ends when length - 1 bytes have been read, on a newline, or on EOF (whichever comes first).

Return

The fgets() function returns a string of up to length - 1 bytes read from the file pointed to by fle_pointer.

Example

The following is an example. Here, we have a file “one.txt” with text “This is it!”.

<?php
   $file_pointer = @fopen("/new/one.txt", "w");
   if ($file_pointer) {
      while (!feof($file_pointer)) {
         $buffer = fgets($file_pointer, 512);
         echo $buffer;
      }
      fclose($file_pointer);
   }
?>

Output

This is it!

Let us see another example.

Example

Here, we have a text file “new.txt”, with the text, “This is demo text”.

<?php
   $file_pointer = fopen("new.txt","r");
   $res = fgets($file_pointer);
   echo $res;
   fclose($file_pointer);
?>

Output

This is demo text

karthikeya Boyini
karthikeya Boyini

I love programming (: That's all I know

Updated on: 24-Jun-2020

349 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements