将.csv文件读入Laravel中的数组

And*_*dre 9 php laravel laravel-5

我在Laravel 5中的这个目录中存储了一个.csv文件:

/storage/app/data.csv

在这个函数里面我试着读取这个文件的内容并从中提取几个列,比如名称和城市到数组,示例代码:

use Illuminate\Support\Facades\Storage;

public function get_data() {

 $file_n = Storage::url('data.csv');
 $file = fopen($file_n, "r");
 $all_data = array();
 while ( ($data = fgetcsv($file, 200, ",")) !==FALSE {

     $name = $data[0];
     $city = $data[1];
     $all_data = $name. " ".$city;

     array_push($array, $all_data);
  }
  fclose($file);
}
Run Code Online (Sandbox Code Playgroud)

我在Controller中收到ErrorException:

fopen(/storage/data.csv): failed to open stream: No such file or directory
Run Code Online (Sandbox Code Playgroud)

但文件就在那里.有没有更好的方法来做到这一点?

谢谢你的期待!

And*_*dre 9

我通过使用“storage_path”找到了它。

...
$filename = storage_path('/app/data.csv');
$file = fopen($filename, "r");
$all_data = array();
while ( ($data = fgetcsv($file, 200, ",")) !==FALSE ) {
    ...
}
Run Code Online (Sandbox Code Playgroud)

谢谢!


Val*_*zer 7

你的问题与前面人们所指出的一样.

您可以使用辅助函数storage_path https://laravel.com/docs/5.3/helpers#method-storage-path

在您的情况下,它将像这样使用:

storage_path('app/data.csv');
Run Code Online (Sandbox Code Playgroud)

作为推荐,您可以使用此库来处理CSV/Excel文件,它非常易于使用:https://github.com/Maatwebsite/Laravel-Excel


Use*_*356 6

Laravel 5.7 试试这个:

Storage::disk('local')->path('import.csv');
Run Code Online (Sandbox Code Playgroud)

应该不错。