0

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

1 Answer 1

2

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.
Sign up to request clarification or add additional context in comments.

1 Comment

I found a better use , I am ganna use Laravel-Excel packages , thanks for the help

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.