开发者

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

This question already has answers here: Reading very large files in PHP (开发者_开发知识库8 answers) Closed 8 years ago.

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

How can i read such giant text files from PHP?


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);
?>


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);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜