How to read giant text file in PHP? [duplicate]

佐手、 提交于 2019-12-11 04:56:57

问题


I have few text files with size more than 30MB.

How can i read such giant text files from PHP?


回答1:


Unless you need to work with all the data at the same moment, you can read them in pieces. Example for binary files:

<?php
$handle = fopen("/foo/bar/somefile", "rb");
$contents = '';
while (!feof($handle)) {
  $block = fread($handle, 8192);
  do_something_with_block($block);
}
fclose($handle);
?>

The above example might break multibyte encodings (in case there's a multibyte character across the 8192-byte boundary - e.g. Ǿ in UTF-8), so for files that have meaningful endlines (e.g. text), try this:

<?php
$handle = fopen("/foo/bar/somefile", "rb");
$contents = '';
while (!feof($handle)) {
  $line = fgets($handle);
  do_something_with_line($line);
}
fclose($handle);
?>



回答2:


You can open the file using fopen, read the lines using fgets.

$fh = fopen("file", "r");  // open file to read.

while (!feof($fh)) { // loop till lines are left in the input file.
        $buffer = fgets($fh); //  read input file line by line.
        .....
        }       
}       

fclose($fh);


来源:https://stackoverflow.com/questions/3674645/how-to-read-giant-text-file-in-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!