I have been looking for how to find a value in one line and return the value of another column in a CSV file.
This is my function and it works fine but in small files:
function find_user($filename, $id) {
$f = fopen($filename, "r");
$result = false;
while ($row = fgetcsv($f, 0, ";")) {
if ($row[6] == $id) {
$result = $row[5];
break;
}
}
fclose($f);
return $result;
}
The problem is that the actual file with which I must work has a size of 4GB. And the time it takes to search is tremendous.
Navigating through Stack Overflow, I found the following post: file_get_contents => PHP Fatal error: Allowed memory exhausted
There they give me the following function that (from what I understood) makes it easier for me to search for huge CSV values:
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;
}
And the way of using it seems to be the following:
$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
}
The problem is that I do not know how to adapt my initial code to work with the raised function to speed up the search in large CSVs. My knowledge in PHP is not very advanced.