Reputation: 1745
Hi I am trying to export database table users to a csv file and I am using the following method in my controller:
public function getExport()
{
$table = User::all();
$output='';
foreach ($table as $row) {
$output.= implode(",",$row->toArray());
}
$headers = array(
'Content-Type' => 'text/csv',
'Content-Disposition' => 'attachment; filename="ExportFileName.csv"',
);
return Response::make(rtrim($output, "\n"), 200, $headers);
}
but when I open "ExportFileName.csv" I am getting not Columns Headers and also getting some other garbage in there that are not in the database ?
Whats the best and easy way to do this in Laravel 4
Thanks
Upvotes: 0
Views: 1230
Reputation: 981
You've not added the headers to the CSV. Before outputting the rows, you should do something like:
foreach ($table[0] as $column => $value) {
$output .= "$column,";
}
rtrim($output, ",");
$output .= "\n";
(There are better ways to do that).
You'll also need to account for special characters in the values:
""
to deal with commas,\n
s.Upvotes: 2