Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read file contents with Laravel

Tags:

php

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.

like image 721
Tristan Avatar asked Nov 04 '14 08:11

Tristan


4 Answers

You can use simple PHP:

foreach(file('yourfile.txt') as $line) {
    // loop with $line for each line of yourfile.txt
}
like image 119
KyleK Avatar answered Oct 14 '22 06:10

KyleK


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 
}
like image 26
Victor Axelsson Avatar answered Oct 14 '22 05:10

Victor Axelsson


You can use

try
{
    $contents = File::get($filename);
}
catch (Illuminate\Contracts\Filesystem\FileNotFoundException $exception)
{
    die("The file doesn't exist");
}
like image 2
toni rmc Avatar answered Oct 14 '22 05:10

toni rmc


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
}

like image 1
Albert Abdonor Avatar answered Oct 14 '22 05:10

Albert Abdonor