Skip to content

Instantly share code, notes, and snippets.

@moloy666
Created April 27, 2024 11:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save moloy666/4342cf66b7d047bf39f9e45f392ff354 to your computer and use it in GitHub Desktop.
Save moloy666/4342cf66b7d047bf39f9e45f392ff354 to your computer and use it in GitHub Desktop.
convert data to csv in yii
$dataProvider = $this->getPendingBookingsDataProvider();
$models = $dataProvider->getModels();
Yii::$app->response->format = Response::FORMAT_RAW;
Yii::$app->response->headers->set('Content-Type', 'text/csv');
Yii::$app->response->headers->set('Content-Disposition', 'attachment; filename="data.csv"');
Yii::$app->response->send();
$csvHeader = ['#', 'Customer', 'Contact', 'Camp Name', 'Event Name', 'Check In', 'Total Price', 'Created At', 'Status'];
$csvData[] = $csvHeader;
foreach ($models as $i => $model) {
$rowData = [];
$rowData[] = $i + 1;
$rowData[] = ucwords($model->customer->name);
$rowData[] = $model->customer->username;
$rowData[] = ucwords((empty($model->camp_id)) ? 'NA' : $model->camp->name);
$rowData[] = ucwords((empty($model->event_id)) ? 'NA' : $model->event->name);
$rowData[] = date('jS M Y', strtotime($model->from_date));
$rowData[] = $model->total_price;
$rowData[] = date('jS M Y h:i A', strtotime($model->created_at));
$rowData[] = 'Pending';
$csvData[] = $rowData;
}
$outputBuffer = fopen('php://output', 'w');
foreach ($csvData as $fields) {
fputcsv($outputBuffer, $fields);
}
fclose($outputBuffer);
Yii::$app->end();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment