Laravel 5.6 how to read text file line by line

Viewed 21655

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?

5 Answers

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

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

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.

Hope it will help

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