We can export a database table Data using
We can two route functions for this:
Thanks
Laravel
as a csv
file. I will show you how can we create a csv download link in laravel and we can export table data in csv.We can two route functions for this:
1. Route::get('/all-data-csv', function() {
$tweets = Table::all();
// the csv file with the first row
$output = implode(",", array('text', 'screen name', 'name', 'created at'));
foreach ($tweets as $row) {
// iterate over each tweet and add it to the csv
$output .= implode(",", array($row['tweet_text'], $row['screen_name'], $row['name'], $row['created_at'])); // append each row
}
// headers used to make the file "downloadable", we set them manually
// since we can't use Laravel's Response::download() function
$headers = array(
'Content-Type' => 'text/csv',
'Content-Disposition' => 'attachment; filename="tweets.csv"',
);
// our response, this will be equivalent to your download() but
// without using a local file
return Response::make(rtrim($output, "\n"), 200, $headers);
});
2. Route::get('/all-tabe-csv', function(){
$table = Table::all();
$filename = "data.csv";
$handle = fopen($filename, 'w+');
fputcsv($handle, array('tweet text', 'screen name', 'name', 'created at'));
foreach($table as $row) {
fputcsv($handle, array($row['tweet_text'], $row['screen_name'], $row['name'], $row['created_at']));
}
fclose($handle);
$headers = array(
'Content-Type' => 'text/csv',
);
return Response::download($handle, 'data.csv', $filename);
});
Thanks
No comments:
Post a Comment