Tristan
Tristan

Reputation: 368

Read file contents with Laravel

I am trying to read the contents of a file line by line with Laravel. However, I can't seem to find anything about it anywhere.

Should I use the fopen function or can I do it with the File::get() function?

I've checked the API but there doesn't seem to have a function to read the contents of the file.

Upvotes: 32

Views: 97535

Answers (7)

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: 1

sorosh arbabi
sorosh arbabi

Reputation: 32

$tmpName = $request->file('csv_file');
$csvAsArray = array_map('str_getcsv', file($tmpName));

Upvotes: -2

Netwons
Netwons

Reputation: 1648

You can use

 file_get_contents(base_path('app/Http/Controllers/ProductController.php'), true);

Upvotes: 1

Albert Abdonor
Albert Abdonor

Reputation: 959

you can do something like this:


$file = '/home/albert/myfile.txt';//the path of your file
$conn = Storage::disk('my_disk');//configured in the file filesystems.php
$stream = $conn->readStream($file);
while (($line = fgets($stream, 4096)) !== false) {
   //$line is the string var of your line from your file
}

Upvotes: 3

KyleK
KyleK

Reputation: 5131

You can use simple PHP:

foreach(file('yourfile.txt') as $line) {
    // loop with $line for each line of yourfile.txt
}

Upvotes: 35

toni rmc
toni rmc

Reputation: 878

You can use

try
{
    $contents = File::get($filename);
}
catch (Illuminate\Contracts\Filesystem\FileNotFoundException $exception)
{
    die("The file doesn't exist");
}

Upvotes: 2

Victor Axelsson
Victor Axelsson

Reputation: 1466

You can use the following to get the contents:

$content = File::get($filename);

Which will return a Illuminate\Filesystem\FileNotFoundException if it's not found. If you want to fetch something remote you can use:

$content = File::getRemote($url);

Which will return false if not found.

When you have the file you don't need laravel specific methods for handling the data. Now you need to work with the content in php. If you wan't to read the lines you can do it like @kylek described:

 foreach($content as $line) {
    //use $line 
}

Upvotes: 27

Related Questions