0

I want to ask how can I get the first row (the column names) in laravel? For now I load my file from storage. I have tried $contents[0]; but it did not work.

public function csvread(Request $request) {
$contents = Storage::disk('public')->get('asdf.csv');
}

Thanks!

Martin
  • 1,063
  • 1
  • 15
  • 30
  • 1
    Something wrong with [fgetcsv](http://php.net/fgetcsv)? – Jonnix Jun 29 '16 at 14:30
  • Have you ascertained if the call you are making is successful? Try dumping the value of `$contents` to make sure you are getting an expected value. I am not familiar with Laravel but I speculate it either returns some sort of file object, or `false` if not successful... Or, are you getting an error message? If so you should add it to the question for reference. – Darragh Enright Jun 29 '16 at 14:42

1 Answers1

3

I don't know Laravel so I cannot comment specifically on the functionality of Storage. However, I had a look at the documentation, which states the following:

The get method may be used to retrieve the contents of a given file. The raw string contents of the file will be returned by the method

So, assuming the call you made successfully found and read a file, $contents is a string - and dereferencing $contents[0] is just going to return the first character of the string. Not what you want, clearly!

I concur wth @JonStirling in the question comments and try to parse the csv directly with fgetcsv(). Or, if you want to be more object-based you could use SplFileObject() which can read and iterate over CSV files, given the appropriate flags.

Here's a copy of example #2 from the PHP docs:

$file = new SplFileObject("animals.csv");
$file->setFlags(SplFileObject::READ_CSV);
foreach ($file as $row) {
    list($animal, $class, $legs) = $row;
    printf("A %s is a %s with %d legs\n", $animal, $class, $legs);
}

You'll need the orignal filepath to pass to SplFileObject() too of course - this answer should be useful

Finally, if your CSV has empty lines, you might have to add additional flags to SplFileObject - namely SplFileObject::SKIP_EMPTY and SplFileObject::READ_AHEAD

You may also opt to use a pre-existing package; e.g: http://csv.thephpleague.com/

Hope this helps! :)

Community
  • 1
  • 1
Darragh Enright
  • 12,194
  • 6
  • 37
  • 44
  • Thank you very much for your time. I had some problems with getting url of my file, even with your link to question about it. But finally I've solved it. Your answer is very exhaustive. – Martin Jun 30 '16 at 06:58
  • Hey, I have one more question is there any posibility to check if one of the columns is named 'name' or 'surname' ? – Martin Jun 30 '16 at 07:06
  • Hi. Just saw this. It depends on your data but assuming your the first line of your csv contains a "header" row, you could check that the first row contains "surname" with `in_array()`? – Darragh Enright Jun 30 '16 at 21:50