I have stored a .csv file in this directory in Laravel 5 :
/storage/app/data.csv
Inside of this function I am trying to read the contents of this file and extract a few columns from it, like name and city to an array, sample code:
use Illuminate\Support\Facades\Storage;
public function get_data() {
$file_n = Storage::url('data.csv');
$file = fopen($file_n, "r");
$all_data = array();
while ( ($data = fgetcsv($file, 200, ",")) !==FALSE {
$name = $data[0];
$city = $data[1];
$all_data = $name. " ".$city;
array_push($array, $all_data);
}
fclose($file);
}
I am getting an ErrorException in Controller:
fopen(/storage/data.csv): failed to open stream: No such file or directory
But the file is there. Is there a better way to do this instead?
Thanks for looking!
You can open the file using fopen() as usual, get each line by using fgets() and then simply explode it on each comma like this: <? php $handle = @fopen("/tmp/inputfile. txt", "r"); if ($handle) { while (($buffer = fgets($handle)) !==
This is step by step tutorial in laravel 8 about CSV file reading. Let’s get started following example. Let’s consider a .csv file in application. We have a users.csv inside /storage folder. You can place this .csv file either in /storage folder or /public folder. We will read only by specifying the path.
Alternatively, you can use the array_map () function to read a CSV file into an array. To do this, you'll use str_getcsv as a callback function. This is a built-in PHP function that is used to parse a CSV string into an array. A callback function is some executable code that is passed to another piece of code as an argument.
We'll use fopen () and fgetcsv () to read the contents of a CSV file, and then we'll convert it into an array using the array_map () and str_getcsv () functions. Storing data files in comma-separated values (CSV) format is no new thing.
We then call the readDocument function, which passes the CSV document as a parameter, and next, the contents of the CSV file are displayed as below: Alternatively, you can use the array_map () function to read a CSV file into an array. To do this, you'll use str_getcsv as a callback function.
Your issue is with the path as previous people pointed out.
You can use the helper function storage_path https://laravel.com/docs/5.3/helpers#method-storage-path
In your case it will be used like this:
storage_path('app/data.csv');
As a recomendation you can use this libary to work with CSV/Excel files, it's pretty easy to use: https://github.com/Maatwebsite/Laravel-Excel
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With