简体   繁体   English

将数据库表导出到CSV Laravel

[英]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: 嗨,我正在尝试将数据库表用户导出到一个csv文件,并且我在控制器中使用以下方法:

 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 ? 但是,当我打开“ ExportFileName.csv”时,我没有列标题,并且在那里也得到了数据库中没有的其他垃圾?

Whats the best and easy way to do this in Laravel 4 Laravel 4中做到这一点的最佳和简便方法是什么

Thanks 谢谢

You've not added the headers to the CSV. 您尚未将标题添加到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 \\n s. 删除或替换任何\\n

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM