问题描述
我已经在Laravel 5的此目录中存储了一个.csv文件:
I have stored a .csv file in this directory in Laravel 5 :
/storage/app/data.csv
/storage/app/data.csv
在此功能内,我尝试读取此文件的内容并从中提取一些列,例如名称和城市到数组中,示例代码:
Inside of this function I am trying to read the contents of this file and extract a few columns from it, like name and city to an array, sample code:
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);
}
我在Controller中收到ErrorException:
I am getting an ErrorException in Controller:
fopen(/storage/data.csv): failed to open stream: No such file or directory
但是文件在那里.有更好的方法代替吗?
But the file is there. Is there a better way to do this instead?
感谢您的光临!
推荐答案
您的问题出在前人所指出的道路上.
Your issue is with the path as previous people pointed out.
您可以使用辅助函数storage_path https://laravel.com/docs/5.3/helpers#method-storage-path
You can use the helper function storage_pathhttps://laravel.com/docs/5.3/helpers#method-storage-path
在您的情况下,它将像这样使用:
In your case it will be used like this:
storage_path('app/data.csv');
作为推荐,您可以使用此库来处理CSV/Excel文件,它非常易于使用: https://github.com/Maatwebsite/Laravel-Excel
As a recomendation you can use this libary to work with CSV/Excel files, it's pretty easy to use: https://github.com/Maatwebsite/Laravel-Excel
这篇关于将.csv文件读入Laravel中的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!