How to read file line by line in PHP?

by cali_green , in category: PHP General , 5 months ago

How to read file line by line in PHP?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by ryan.murray , 3 months 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();
}