码农之家

php大文件如何读

php中处理读取大文件的时候,我们如果一下子全部读,将会造成意想不到的错误。

例如,这个文件超过1GB,这个时候我们需要采取什么策略来解决这个问题呢?

我们可以逐行的读

下面的实现代码,使用fgets()函数逐行读取文件:

$handle = fopen("inputfile.txt", "r");
if ($handle) {
    while (($line = fgets($handle)) !== false) {
        // process the line read.
    }

    fclose($handle);
} else {
    // error opening the file.
} 

代码释义: