Laravel 5.6 如何逐行读取文本文件

5
没有 Laravel,我可以使用简单的代码逐行读取文本文件:
$file = fopen("whatever/file.txt", "r") or exit("Unable to open file!");

while(!feof($file)) {
   echo fgets($file). "<br>";
}

fclose($file);

使用Laravel,由于本地文件存储位置的原因,这个简单的事情变得非常困难。
例如,我可以使用Storage::get('whatever/file.txt')方法获取文件内容,但是如何仅获取一个文件并在循环中读取它呢?
我尝试使用File::get('whatever/file.txt')方法,但是出现错误:File does not exist at path
如何使用Laravel从本地存储(而不是公共存储)逐行读取文件?
6个回答

9
您可以通过以下方式获取您的文件:
$file = fopen(storage_path("whatever/file.txt"), "r");

这将导致类似于以下路径:'/var/www/storage/whatever/file.txt''/var/www/foo/storage/whatever/file.txt'。如果您从同一台服务器提供多个网站,则取决于您的设置,但您可以理解它。然后您就可以读取您的文件。
while(!feof($file)) {
    echo fgets($file). "<br>";
}

fclose($file);

storage_path 返回了不正确的路径目标... 请参见链接:https://dev59.com/Ya_la4cB1Zd3GeqPsGIi#53008932 - mr.boris
我认为这可能有点旧了,但是看看这个链接:https://josephsilber.com/posts/2020/07/29/lazy-collections-in-laravel - Ahmed Aboud

5

Laravel v9.0 更新

File::lines('whatever/file.txt')->each(function ($line) {
    $this->info($line);
});

3

您需要知道文件所在的位置,还需要路径才能到达那里。 例如,如果您的文件位于存储文件夹中,可以执行以下操作:

File::get(storage_path('whatever/test.txt'));
dd($contents);

对我来说不起作用。$file = Storage::get("whatever/test.txt"); 可以很好地获取文件内容,但是 $file = File::get(storage_path('whatever/test.txt')); 返回错误:File does not exist at path - mr.boris
@mr.boris 你需要检查你的文件路径。 - Problem Solver

2
    $files = ExamFile::where('exam',$code)->get();
    foreach ($files as $file)
    {
        $content = fopen(Storage::path($file->url),'r');

        while(!feof($content)){

            $line = fgets($content);

            echo $line."<br>";
        }

        fclose($content);
    }

您可以像这样使用它。对我有效。

1
希望它有所帮助。
  File::get(storage_path('whatever/file.txt'));

1

太令人困惑了!

我的文件在文件夹storage/app/whatever/file.txt中,但是Laravel的storage("whatever/file.txt")方法将其识别为storage/whatever/file.txt路径。

正如我之前所说,这让人不知所措和困惑。

因此,fopen('storage/app/whatever/file.txt')对我有用。


3
你本可以使用storage_path('app/whatever/file.text')代替。 - thisiskelvin

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接