我一直在寻找如何在一行中查找值并返回CSV文件中另一列的值。在PHP中短时间解析大型CSV文件
这是我的功能,它工作正常,但在小档案:
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;
}
的问题是,与我必须工作的实际文件的大小为4GB。而搜索所花的时间是巨大的。
通过堆栈溢出导航,我发现下面的帖子: file_get_contents => PHP Fatal error: Allowed memory exhausted
在那里,他们给我下面的函数(从我的理解),使我更容易搜索巨大的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
}
的问题是,我不知道如何调整我的初始代码以使用凸起的函数来加速大型CSV中的搜索。我在PHP方面的知识不是很先进。
以4096字节块读取文件可能不会加快速度,因为每次要搜索时都必须通读整个文件。您最好将文件导入数据库一次,并使用数据库快速搜索自身的能力。 – kmoser
尝试在参数2中添加一个长度,其中的值是该行的长度,并查看是否生成差异,例如'''$ row = fgetcsv($ f,1024,“;”)'''' – crafter