I am new to Laravel and I am trying to create a CSV file using the below code. The problem I am facing is that I am getting a blank row at the top of the CSV file. Please see my code here:
$fileName = 'Feedback.csv';
$AllFeedData = $this->GetData($datefrom,$dateto,$screen);
$headers = array(
"Content-type" => "text/csv",
"Content-Disposition" => "attachment; filename=$fileName",
"Pragma" => "no-cache",
"Cache-Control" => "must-revalidate, post-check=0, pre-check=0",
"Expires" => "0"
);
$columns = array('MRN No', 'Patient Name', 'Gender', 'Age', 'Doctor', 'Total Rating', 'Feedback Status', 'Question', 'Rating', 'Mobile', 'Email', 'Invoice No', 'Invoice Date');
try
{
$callback = function() use($AllFeedData, $columns) {
$file = fopen('php://output', 'r+');
fputcsv($file, $columns);
foreach ($AllFeedData as $AllData) {
$row['MRN No'] = $AllData->pfc_ptno;
$row['Patient Name'] = $AllData->pfc_ptname;
if($AllData->pfc_gender == 'F'){
$row['Gender'] = 'Female';
}elseif ($AllData->pfc_gender == 'M'){
$row['Gender'] = 'Male';
}else{
$row['Gender'] = 'Other';
}
$row['Age'] = $AllData->pfn_yearage;
$row['Doctor'] = $AllData->pfc_docname;
$row['Total Rating'] = $AllData->pfn_totrating;
if($AllData->pfc_status == "F"){
$row['Feedback Status'] = 'Completed';
}elseif ($AllData->pfc_status == "P"){
$row['Feedback Status'] = 'Partially Completed';
}elseif ($AllData->pfc_status == "N"){
$row['Feedback Status'] = 'Pending';
}
$row['Question'] = $AllData->qfc_question;
$row['Rating'] = $AllData->pfn_rating;
$row['Mobile'] = $AllData->pfc_mobile;
$row['Email'] = strtolower($AllData->pfc_email);
$row['Invoice No'] = $AllData->pfc_invno;
$row['Invoice Date'] = $AllData->pfd_invdate;
fputcsv($file, array($row['MRN No'], $row['Patient Name'], $row['Gender'], $row['Age'], $row['Doctor'], $row['Total Rating'], $row['Feedback Status'], $row['Question'], $row['Rating'], $row['Mobile'], $row['Email'], $row['Invoice No'], $row['Invoice Date']));
}
fclose($file);
};
}
catch (Exception $e) {
report($e);
return false;
}
return response()->stream($callback, 200, $headers);
}
Screenshot of the exported CSV file is attached below. Please note the highlighted row which I need to be removed.