【问题标题】:Read a .csv file into an array in Laravel将 .csv 文件读入 Laravel 中的数组
【发布时间】:2019-07-07 07:25:02
【问题描述】:

我在 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);
}

我在控制器中得到一个 ErrorException:

fopen(/storage/data.csv): failed to open stream: No such file or directory

但是文件在那里。有没有更好的方法来代替?

感谢收看!

【问题讨论】:

  • 试试storage_path('data.csv')
  • /storage/app/data.csv != /storage/data.csv
  • 如果您需要为此使用 Storage 类,特别是如果您使用 s3 或 minio,请尝试 \Storage::disk('local_temp')->getDriver()->getAdapter()->applyPathPrefix($this->fileName); 获取完整文件路径。这是 Laravel 5.1 的解决方案,对于 Laravel 5.2 及更高版本,::url() 函数可以工作。对于 Laravel 5.7 及更高版本,::path() 函数将起作用。

标签: php laravel laravel-5


【解决方案1】:

您的问题在于前面的人指出的路径。

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

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

storage_path('app/data.csv');

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

【讨论】:

    【解决方案2】:

    Laravel 5.7 试试这个:

    Storage::disk('local')->path('import.csv');
    

    应该不错。

    【讨论】:

      【解决方案3】:

      我通过使用“storage_path”解决了这个问题。

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

      谢谢!

      【讨论】:

        【解决方案4】:

        我通过在 config/filesystems.php 中向我的本地磁盘配置添加一个 url 键解决了这个问题,如下所示:

            'local' => [
                'driver' => 'local',
                'root' => storage_path('app'),
                'url' => storage_path('app')
            ],
        

        现在我可以引用 Storage::url('filename.txt') 并返回:

            /home/josh/apps/storage/app/filename.txt
        

        【讨论】:

          【解决方案5】:

          试试下面的

          $file_n = Storage::get('data.csv');
          

          【讨论】:

          • 这会将 csv 文件作为字符串返回。
          猜你喜欢
          • 2011-05-16
          • 1970-01-01
          • 1970-01-01
          • 2019-08-24
          • 1970-01-01
          • 2013-12-11
          • 2014-09-13
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多