user3150060
user3150060

Reputation: 1745

export database table to csv laravel

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

Answers (1)

Chris
Chris

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:

  • Wrap every value in "" to deal with commas,
  • Escape and quotation marks, and
  • Delete or replace any \ns.

Upvotes: 2

Related Questions