Skip to content

Instantly share code, notes, and snippets.

@lastday154
Created March 2, 2018 04:50
Show Gist options
  • Select an option

  • Save lastday154/65fcee25bc81c7489e9a021e3cc2b1d4 to your computer and use it in GitHub Desktop.

Select an option

Save lastday154/65fcee25bc81c7489e9a021e3cc2b1d4 to your computer and use it in GitHub Desktop.
Read big file csv
function file_get_contents_chunked($file,$chunk_size,$callback)
{
try
{
$handle = fopen($file, "r");
$i = 0;
while (!feof($handle))
{
call_user_func_array($callback,array(fread($handle,$chunk_size),&$handle,$i));
$i++;
}
fclose($handle);
}
catch(Exception $e)
{
trigger_error("file_get_contents_chunked::" . $e->getMessage(),E_USER_NOTICE);
return false;
}
return true;
}
$success = file_get_contents_chunked("my/large/file",4096,function($chunk,&$handle,$iteration){
/*
* Do what you will with the {&chunk} here
* {$handle} is passed in case you want to seek
** to different parts of the file
* {$iteration} is the section fo the file that has been read so
* ($i * 4096) is your current offset within the file.
*/
});
if(!$success)
{
//It Failed
}
https://stackoverflow.com/questions/5249279/file-get-contents-php-fatal-error-allowed-memory-exhausted/5249971#5249971
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment