Pavinder's avatar

Import and Export CSV File.

I want to upload csv file into my laravel app, after this i need to add some new columns into those records and export that data as csv file. i don't want to store it into the database. real issue is how can i add new columns to csv file and export merged csv file. please suggeset any solution.

0 likes
3 replies
frankincredible's avatar

I'd look into using this package: https://csv.thephpleague.com/

Basically, you'd read the file, map the resulting iterable records to include your new column, then re-write the file.

$reader = Reader::createFromPath('/path/to/my/file.csv', 'r');
$reader->setHeaderOffset(0);
$records = $reader->getRecords();

// $records is now an iterable  object that has the columns from row 0 as its indexes:
// Example: 
// foreach ($records as $offset => $record) {
//    $offset : represents the record offset
//    var_export($record) returns something like
//    [
//        'First Name' => 'jane',
//        'Last Name' => 'doe',
//        'E-mail' => '[email protected]'
//    ];
// }

// I'd probably collect($records->map(function($record, $row){ }); to map a new array of records (of course making sure to create new headers as well when you write your new document.


$writer = Writer::createFromPath('/path/to/saved/newfile.csv', 'w+');
$writer->insertAll($records); //using an array, assuming you prepended headers to this array.

This was pseudo code, of course, but it should get you moving.

Please or to participate in this conversation.