How to read file line by line in PHP?

by cali_green , in category: PHP General , 2 years ago

How to read file line by line in PHP?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

by ryan.murray , a year ago

@cali_green use SplFileObject class to read any file line by line in PHP, here is the code:


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
<?php

// Path to file
$path = "test.txt";

// Create instance of SplFileObject object
$file = new SplFileObject($path);

// Loop until end of file.
while (!$file->eof()) {
    // Print line
    echo $file->fgets();
}


Member

by daisha , 7 months ago

@cali_green 

To read a file line by line in PHP, you can use the fgets() function inside a loop. Here's an example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
$file = fopen("your_file.txt", "r"); // open the file in read mode

if ($file) {
    while (($line = fgets($file)) !== false) {
        // process each line
        echo $line;
    }
    
    fclose($file); // close the file
} else {
    echo "Error opening the file";
}


In this example, we first open the file using the fopen() function with the file path and "r" (read mode) as parameters. Then, we check if the file is successfully opened.


Inside the while loop, we use fgets() to read each line of the file. The fgets() function returns the current line as a string and moves the pointer to the next line. The loop continues until there are no more lines to read.


You can then process each line as needed. In this example, we just echo the line.


Finally, don't forget to close the file using the fclose() function to free up system resources.