【问题标题】:open and read a csv file from storage path and convert it into mysql table in php laravel从存储路径打开并读取一个csv文件并将其转换为php laravel中的mysql表
【发布时间】:2018-07-07 08:12:12
【问题描述】:
if (($file = Storage :: get('/logos/ ' . $filename )) !== FALSE) {
     while ( ($data = fgetcsv($file, 1000, ",")) !==FALSE )
     {
        $csv_data = new Issue();
        $csv_data->id = $data [0];
        $csv_data->firstname = $data [1];
        $csv_data->lastname = $data [2];
        $csv_data->email = $data [3];
        $csv_data->gender = $data [4];
        $csv_data->save ();
    }
    fclose($file);   
}

上面的代码给了我以下错误:

fgetcsv() 期望参数 1 是资源,给定字符串"

【问题讨论】:

    标签: php laravel csv import upload


    【解决方案1】:
    在@Naeem 评论后

    编辑(谢谢)。

    $file 是内容,而不是文件指针。您可以使用 str_getcsv() 解析 CSV 行:

    $data = Storage::get('/logos/' . $filename);
    $csv = array_map(function($row) {
        $data = str_getcsv($row) ;
        $csv_data = new Issue();
        $csv_data->id = $data [0];
        $csv_data->firstname = $data [1];
        $csv_data->lastname = $data [2];
        $csv_data->email = $data [3];
        $csv_data->gender = $data [4];
        $csv_data->save ();
    }, explode("\n", $data)); 
    

    可能\n 应该使用 (PHP_EOL) 的 \r\n 更新,具体取决于 CSV 的换行符。

    如果你只想要第一行(通常是标题),你可以使用:

    $data = Storage::get('/logos/ ' . $filename);
    $lines = explode("\n", $data, 2) ; // create an array of 2 entry (first line, and the rest).
    $first_line = reset($lines);
    
    $data = str_getcsv($first_line) ;
    $csv_data = new Issue();
    $csv_data->id = $data [0];
    $csv_data->firstname = $data [1];
    $csv_data->lastname = $data [2];
    $csv_data->email = $data [3];
    $csv_data->gender = $data [4];
    $csv_data->save();
    

    【讨论】:

    • 此解决方案不起作用。您已经在 Storage::get 上读取文件,该文件返回 $content 而不是 $file
    • 感谢@Naeem 的反馈。我已经更新了答案。你能告诉我它现在是否有效吗?如果没有,我会删除这个答案。谢谢!
    • 感谢您的更新。如果我只想读取第一行意味着只有标题行而不是整个文件怎么办?
    • @Naeem 我已更新答案以仅获取标题行。
    • $first_line : 然后再用 "," 爆炸?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多