我一直在尋找如何在一行中查找值並返回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