Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 5.6 how to read text file line by line

Tags:

file

php

laravel

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?

like image 623
mr.boris Avatar asked Dec 14 '22 14:12

mr.boris


1 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);
like image 88
Sasa Blagojevic Avatar answered Dec 18 '22 00:12

Sasa Blagojevic