2017-08-28 90 views
2

我一直在尋找如何在一行中查找值並返回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方面的知識不是很先進。

+0

以4096字節塊讀取文件可能不會加快速度,因爲每次要搜索時都必須通讀整個文件。您最好將文件導入數據庫一次,並使用數據庫快速搜索自身的能力。 – kmoser

+0

嘗試在參數2中添加一個長度,其中的值是該行的長度,並查看是否生成差異,例如'''$ row = fgetcsv($ f,1024,「;」)'''' – crafter

回答

2

無論您如何閱讀文件,都無法更快地進行搜索,因爲您必須在搜索正確的行和列的同時掃描每個字符。最糟糕的情況是,你正在查找的行是文件中的最後一行。

您應該將CSV導入適當的索引數據庫並修改您的應用程序以進一步將新記錄保存到該數據庫而不是CSV文件。

這是一個使用SQLite的基本示例。我創建了一個包含1億條記錄(〜5GB)的CSV文件並進行了測試。

創建一個SQLite數據庫並導入CSV文件導入它:

$f = fopen('db.csv', 'r'); 
$db = new SQLite3('data.db'); 
$db->exec('CREATE TABLE "user" ("id" INT PRIMARY KEY, "name" TEXT, 
    "c1" TEXT, "c2" TEXT, "c3" TEXT, "c4" TEXT, "c5" TEXT)'); 
$stmt = $db->prepare('INSERT INTO "user" 
    ("id", "name", "c1", "c2", "c3", "c4", "c5") VALUES (?, ?, ?, ?, ?, ?, ?)'); 
$stmt->bindParam(1, $id, SQLITE3_INTEGER); 
$stmt->bindParam(2, $name, SQLITE3_TEXT); 
$stmt->bindParam(3, $c1, SQLITE3_TEXT); 
$stmt->bindParam(4, $c2, SQLITE3_TEXT); 
$stmt->bindParam(5, $c3, SQLITE3_TEXT); 
$stmt->bindParam(6, $c4, SQLITE3_TEXT); 
$stmt->bindParam(7, $c5, SQLITE3_TEXT); 
$db->exec('BEGIN TRANSACTION'); 
while ($row = fgetcsv($f, 0, ';')) { 
    list($c1, $c2, $c3, $c4, $c5, $name, $id) = $row; 
    $stmt->execute(); 
} 
$db->exec('COMMIT'); 

這需要很長的時間,在15分鐘內我的電腦上,從而產生一個6.5GB的文件。從數據庫

搜索:

$id = 99999999; 
$db = new SQLite3('data.db'); 
$stmt = $db->prepare('SELECT "name" FROM "user" WHERE "id" = ?'); 
$stmt->bindValue(1, $id, SQLITE3_INTEGER); 
$result = $stmt->execute(); 
print_r($result->fetchArray()); 

這實際上執行instantenously。