Reputation: 368
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
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
Reputation: 32
$tmpName = $request->file('csv_file');
$csvAsArray = array_map('str_getcsv', file($tmpName));
Upvotes: -2
Reputation: 1648
You can use
file_get_contents(base_path('app/Http/Controllers/ProductController.php'), true);
Upvotes: 1
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
Reputation: 5131
You can use simple PHP:
foreach(file('yourfile.txt') as $line) {
// loop with $line for each line of yourfile.txt
}
Upvotes: 35
Reputation: 878
You can use
try
{
$contents = File::get($filename);
}
catch (Illuminate\Contracts\Filesystem\FileNotFoundException $exception)
{
die("The file doesn't exist");
}
Upvotes: 2
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