views:

71

answers:

3

Hello,

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

How can i read such giant text files from PHP?

+1  A: 

http://php.net/fgets has an example

Col. Shrapnel
+3  A: 

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);
codaddict
+6  A: 

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