How can we read a file line by line in PHP?

In PHP, you can read a file line by line using the file() function.

The example code is as follows:

$filename = "example.txt";

$file = fopen($filename, "r");

if ($file) {
    while (($line = fgets($file)) !== false) {
        // 处理每一行的内容
        echo $line;
    }
    
    fclose($file);
} else {
    echo "无法打开文件";
}

In the above code, the file is first opened using the fopen() function with the mode “r” for read-only. If the file is successfully opened, the fgets() function is used to read the content of the file line by line and assign it to the $line variable. By looping through the content, each line of the file can be processed. Finally, the fclose() function is used to close the file.

It is important to note that the file() function can also read all lines of a file into an array at once, making it more concise to use. An example code is as follows:

$filename = "example.txt";
$lines = file($filename);

foreach ($lines as $line) {
    echo $line;
}

This method is suitable for smaller files. For larger files, it is recommended to use the previous method of reading line by line to reduce memory consumption.

bannerAds