php - 在 php 或 Cakephp 中使用 fgetcsv 导入大型 CSV 文件

标签 php mysql cakephp csv fgetcsv

我在导入超过 1,00,000 行的 CSV 文件时遇到问题。我正在使用 fgetcsv 从 CSV 文件中获取数据。

我的要求是先截断表格,从 CSV 文件中获取数据并将其存储在数据库中。但是每次它只获取 40000 到 50000 行。谁能告诉我这是什么问题?我的代码如下,

$destination    = realpath('../../admin/webroot/');
$originalPath   = $destination."/".$this->request->data['Importmodel']['importfile'];

# Get Table Fields
$tableFields = ClassRegistry::init('Systemoption')->getTableDetails($this->request->data['Importmodel']['modeloptions']);

ClassRegistry::init($this->request->data['Importmodel']['modeloptions'])->query("TRUNCATE TABLE " . $this->request->data['Importmodel']['modeloptions']);
$row = 1;
if(($handle = fopen($originalPath, "r")) !== false) {
    try {
        while (($data = fgetcsv($handle, 0, "|")) !== false) {
            $num = count($data);

            if($num != (count($tableFields) - 1)) { 
                unlink($originalPath);
                $this->Session->setFlash("Table \"".$this->request->data['Importmodel']['modeloptions']."\" fields and \"".$fileName."\" fields does not match", 'default', array('class'=>'flash_bad'));
                $this->redirect(array('action' => 'index'));
                exit;
            }

            $queryData = array();
            for ($c=0; $c < $num; $c++) {
                $queryData[$this->request->data['Importmodel']['modeloptions']][$tableFields[$c+1]] = $data[$c];
            }

            ClassRegistry::init($this->request->data['Importmodel']['modeloptions'])->create();
            ClassRegistry::init($this->request->data['Importmodel']['modeloptions'])->save($queryData);
            $row++;
        }
        $result = 1;
    } catch (Exception $e) {
        $result = 0;    
    }
}

if($result == 1) {
    unlink($originalPath);
    $this->Session->setFlash("Table \"" . $this->request->data['Importmodel']['modeloptions'] . "\" data populated successfully", 'default', array('class'=>'flash_good'));
    $this->redirect(array('action' => 'index'));
    exit;
} else {
    $this->Session->setFlash("Error : Table \"" . $this->request->data['Importmodel']['modeloptions'] . "\" data not fully populated", 'default', array('class'=>'flash_bad'));
    $this->redirect(array('action' => 'index'));
    exit;
}

最佳答案

您是从控制台执行此操作吗?如果不是,请尝试增加 php.ini 中的内存和时间限制

关于php - 在 php 或 Cakephp 中使用 fgetcsv 导入大型 CSV 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18912146/

相关文章:

php - mysql数据没有根据html表中的id出现

php - PDO,准备使用

cakephp - 调试在 get 中发送的 CakePHP HttpSocket 数据

php - 如何将 cakephp 2.x 组件和助手转换为 1.3

php - 将 PHP 7 错误对象转换为异常?

php - Laravel 同步多对多关系

php - 选取框显示在两行而不是一行 - HTML 和 CSS

javascript - store如何查询Mysql

mysql - 连接到本地数据库

mysql - 数据库模型所需的建议 - 附加部分 EER