如何用php回显文件的前500行


How do I echo the first 500 lines of a file with php?

这是一个相当大的文件,最终大约有1 GB。

我只想展示前500行。该文件是预先格式化的,因为它是一个日志。

将整个文件分配给数组可能会耗尽机器的内存。

最好根据需要逐行读取文件:

$handle = fopen("data.txt", "r");
if ($handle) {
    for ($i = 0; $i < 500; $i++) {
        if (($line = fgets($handle)) !== false) {
            // Do whatever processing is needed
        }
    }
}

你可以这样做;

<?php
$data = file('data.txt');
for($i=0;$i<500;$i++){
    echo $data[$i];
}
?>