mr.incredible
mr.incredible

Reputation: 4185

Laravel 5.6 how to read text file line by line

Without Laravel I can use simple code to read text file by line:

$file = fopen("whatever/file.txt", "r") or exit("Unable to open file!");

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

fclose($file);

With Laravel this simple thing becomes overwhelming due to local file storage location.

I.e. I can get file contents with Storage::get('whatever/file.txt') method, but how to get just a file and then read it in a loop?

I've tried to use File::get('whatever/file.txt') method but get an error: File does not exist at path.

How to read file from local storage (not public) line by line with Laravel?

Upvotes: 6

Views: 29732

Answers (6)

Rager
Rager

Reputation: 876

Laravel v 10.10 Confirmed working!!

Illuminate\Support\Facades\File::lines(storage_path('app/whatever.txt'))->each(function ($line) {
   $this->info($line);
});

Upvotes: 8

Intorka
Intorka

Reputation: 88

    $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);
    }

You can use it like this. It works for me.

Upvotes: 2

mr.incredible
mr.incredible

Reputation: 4185

So confusing!

My file was in the folder storage/app/whatever/file.txt but Laravel storage("whatever/file.txt") method recognizes it as storage/whatever/file.txt path.

As I said before it is overwhelming and confusing a lot.

So, fopen('storage/app/whatever/file.txt') works for me.

Upvotes: 1

You need to know where your file lives. You also need a path to get there. E.g., if your file is located in the storage folder, you could do

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

Upvotes: 4

Sasa Blagojevic
Sasa Blagojevic

Reputation: 2200

You can get your file like this:

$file = fopen(storage_path("whatever/file.txt"), "r");

This will result in a path similar to this '/var/www/storage/whatever/file.txt' or '/var/www/foo/storage/whatever/file.txt' if you are serving multiple websites from the same server, it will depend on your setup, but you get the gist of it. Then you can read your file;

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

fclose($file);

Upvotes: 11

Prashant Deshmukh.....
Prashant Deshmukh.....

Reputation: 2292

Hope it will help

  File::get(storage_path('whatever/file.txt'));

Upvotes: 1

Related Questions