Facebook Twitter Instagram
    TecAdmin
    • Home
    • FeedBack
    • Submit Article
    • About Us
    Facebook 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.

    Advertisement

    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

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

    How to Compare Two Array Values in PHP: A Practical Guide

    How to Set Up Apache, MySQL, and PHP on macOS: A Comprehensive 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
    • Setting and Getting the Default Timezone in Python
    • What is Media Access Control (MAC) Address?
    • What is Cross-Site Scripting (XSS)?
    • What is Content Security Policy (CSP)?
    • A User’s Guide to Understanding Redirection Operators in Bash
    Facebook Twitter Instagram Pinterest
    © 2023 Tecadmin.net. All Rights Reserved | Terms  | Privacy Policy

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