【问题标题】:CSV upload and change to php array for insert to dbCSV 上传并更改为 php 数组以插入数据库
【发布时间】:2014-04-26 23:06:56
【问题描述】:

所以我想允许用户:

1. Upload a .csv file (mystudents.csv)
2. Import the rows in the .csv
3. Create a PHP array for all this
4. Insert this information into a database

我有以下代码来上传文件并创建数组。

public function studentImport()
{
    ini_set('auto_detect_line_endings', TRUE);

    $config['upload_path'] = './static/files/importFiles';
    $config['allowed_types'] = '*';
    $config['max_size'] = '800';

    $this->load->library('upload', $config);

    if ( ! $this->upload->do_upload())
    {
        var_dump($this->upload->display_errors());
    }
    else
    {
        $data = $this->upload->data();

        $file_path = './static/files/importFiles/'.$data['file_name'];

        $rows = array_map('str_getcsv', file($file_path));
        if($rows){
            $header = array_shift($rows);
            $csv = array();
            foreach($rows as $row) {
                $csv[] = array_combine($header, $row);
            }

            var_dump($csv);
        }
    }
}

文件上传得很好,但错误发生在以下行:$rows = array_map('str_getcsv', file($file_path));

那个错误是:

array_map() [function.array-map]: The first argument, 'str_getcsv', should be either NULL or a valid callback

我需要做什么才能完成这项工作?

【问题讨论】:

    标签: php codeigniter csv


    【解决方案1】:

    函数str_getcsv似乎不可用

    测试一下

    if (function_exists('str_getcsv')) {
      print "str_getcsv defined\n";
    } else {
      print "str_getcsv not defined\n";
    } 
    

    如果函数存在尝试

    $csv= file_get_contents($file_path);
    $array = str_getcsv($csv);
    print json_encode($array);  
    

    $csv= file_get_contents($file_path);
    $array = array_map('str_getcsv', explode("\n", $csv));
    print json_encode($array);  
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-10
      相关资源
      最近更新 更多