'PHP Laravel read csv

I have a CSV file where the data is in landscape orientation.ex:

name, test name
age, 20
gender,Male

where the first column is the headers and the second the data, i tried using laravel maatwebsite/Excel and the response after reading the file, the first row is taken as the headers. (name and test name).

is there any method to read this type of CSV files in laravel using maatwebsite/Excel



Solution 1:[1]

You can use this function

public function readCSV($csvFile, $array)
{
    $file_handle = fopen($csvFile, 'r');
    while (!feof($file_handle)) {
        $line_of_text[] = fgetcsv($file_handle, 0, $array['delimiter']);
    }
    fclose($file_handle);
    return $line_of_text;
}
$csvFileName = "test.csv";
$csvFile = public_path('csv/' . $csvFileName);
$this->readCSV($csvFile,array('delimiter' => ','))

Solution 2:[2]

You don't need an entire library. PHP has a built-in function http://php.net/manual/en/function.str-getcsv.php

Solution 3:[3]

As said by "online Thomas", there's a native PHP function for that, and I find it easiest to use it like so:

$csv = __DIR__ . '/data.csv';
$data = array_map('str_getcsv', file($csv));

Caveat: does not produce the desired results, if fields contain linebreaks

Use closure, if you need a delimiter other than ',' (or other options):

$csv = __DIR__ . '/data.csv';
$data = array_map(function ($line) {
    return str_getcsv($line, ';');
}, file($csv));

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Dharman
Solution 2 online Thomas
Solution 3 s3c