Best practices for importing large CSV files

前端 未结 10 865
攒了一身酷
攒了一身酷 2020-12-14 16:39

My company gets a set of CSV files full of bank account info each month that I need to import into a database. Some of these files can be pretty big. For example, one is abo

10条回答
  •  长情又很酷
    2020-12-14 17:03

    You can use generator for memory efficient file ready. The small snippet below might help you.

    #Method
    public function getFileRecords($params)
    {
        $fp = fopen('../' . $params['file'] . '.csv', 'r');
        //$header = fgetcsv($fp, 1000, ','); // skip header
    
        while (($line = fgetcsv($fp, 1000, ',')) != FALSE) {
            $line = array_map(function($str) {
                return str_replace('\N', '', $str);
            }, $line);
    
            yield $line;
        }
    
        fclose($fp);
    
        return;
    }
    
    #Implementation
    foreach ($yourModel->getFileRecords($params) as $row) {
        // you get row as an assoc array;
        $yourModel->save($row);
    }
    

提交回复
热议问题