使用laravel将整个表导出为CSV

Anu*_*nuj 5 php csv export fputcsv laravel-3

我是laravel的新手,并且很难找到将一个表导出到csv的方法.我在控制器类中尝试了以下代码,但它给了我一个错误:

    public function get_export()
{
    $table = Cpmreport::all();
    $file = fopen('file.csv', 'w');
    foreach ($table as $row) {
        fputcsv($file, $row);
    }
    fclose($file);
    return Redirect::to('consolidated');
}
Run Code Online (Sandbox Code Playgroud)

Cpmreport的模型类:

    class Cpmreport extends Eloquent
    {
      public static $table='cpm_report';
    }
Run Code Online (Sandbox Code Playgroud)

错误 :

    Message:

    fputcsv() expects parameter 2 to be array, object given

    Location:

    C:\xampp\htdocs\cpm_report\application\controllers\cpmreports.php on line 195
Run Code Online (Sandbox Code Playgroud)

任何帮助,将不胜感激.

Din*_*ara 20

简单的方法

Route::get('/csv', function() {
  $table = Cpmreport::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);
});
Run Code Online (Sandbox Code Playgroud)


sqw*_*qwk 7

fputcsv($file, $table);应该fputcsv($file, $row),不应该吗?

并使用Eloquent的to_array()方法将对象转换为数组:http://laravel.com/docs/database/eloquent#to-array

public function get_export()
{
    $table = Cpmreport::all();
    $file = fopen('file.csv', 'w');
    foreach ($table as $row) {
        fputcsv($file, $row->to_array());
    }
    fclose($file);
    return Redirect::to('consolidated');
}
Run Code Online (Sandbox Code Playgroud)