Close Menu
    Facebook X (Twitter) Instagram
    TecAdmin
    • Home
    • FeedBack
    • Submit Article
    • About Us
    Facebook X (Twitter) Instagram
    TecAdmin
    You are at:Home»Programming»PHP»PHP fgets() Function: Read file line by line

    PHP fgets() Function: Read file line by line

    By RahulNovember 2, 20221 Min Read

    PHP fgets() function is used for reading a single line from a file. This function takes two arguments as described below.

    1. File specifies the filename to read content
    2. Length Optional parameter specifies the number of bytes to read from the file.

    Syntax

    PHP fgets() function uses the following syntax.

      fgets(file, length)
    

    Example – Read a single line

    Below are two examples of a reading single line from a file. Use this example to read the complete first-line content from a file.

    1
    2
    3
    4
    5
    6
    <?php
      $fn = fopen("/var/data/myfile.txt","r");
      $result = fgets($fn);
      echo $result;
      fclose($fn);
    ?>

    Instead of a line, you can also define the number of bytes to read from a file:

    1
    2
    3
    4
    5
    6
    <?php
      $fn = fopen("/var/data/myfile.txt","r");
      $result = fgets($fn, 20);
      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 the end of the file.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    <?php
      $fn = fopen("/var/data/myfile.txt","r");
      
      while(! feof($fn))  {
        $result = fgets($fn);
        echo $result;
      }
     
      fclose($fn);
    ?>

    fgets function file PHP php function
    Share. Facebook Twitter Pinterest LinkedIn Tumblr Email WhatsApp

    Related Posts

    Python Program to Copy a File

    How to Disable Functions in PHP

    How to Schedule a Cron Job for PHP: A Step-by-Step Guide

    View 3 Comments

    3 Comments

    1. Pedro on August 26, 2019 12:52 pm

      good article, thanks man!

      Reply
    2. Xaiin on April 28, 2019 12:58 am

      $file should read $fn

      Reply
    3. fu on February 14, 2017 3:44 pm

      $file not define …

      Reply

    Leave A Reply Cancel Reply

    Advertisement
    Recent Posts
    • How to Change Port in Next.Js
    • Ubuntu 24.04 LTS: The Future of Open-Source Excellence
    • How to Execute Linux Commands in Python
    • Creating MySQL User with GRANT OPTION
    • Where to find crontab (cron) logs in Ubuntu & Debian
    Facebook X (Twitter) Instagram Pinterest
    © 2023 Tecadmin.net. All Rights Reserved | Terms  | Privacy Policy

    Type above and press Enter to search. Press Esc to cancel.