I am trying to make a CSV export from a mariaDB database where the web page user can select some optional columns to export. I have a form that captures this data and I have done all the PHP code to get to the point where I have a array of the column headings from my database that I want to use in the export process. ($safefieldsarray is optional fields array from code further above.)
My CSV export is loosly based on this one here https://www.codexworld.com/export-data-to-csv-file-using-php-mysql/ (with the addition of the aforementioned options of what to export.)
The block of code I am struggling with is here.
//create a file pointer
$f = fopen('php://memory', 'w');
//set column headers
$fields = array('ID', 'Name', 'em', 'type', 'reason', 'result', 'status', 'notes', 'datetime', 'requestedby', 'requestedbycitrixid', 'week', 'period', 'year', 'historylog');
$fields = $fields+$safefieldsarray;
fputcsv($f, $fields, $delimiter);
//create $linedata information, formatted in a php assoc row format.
// $linedata1 = implode('"], $exporttocsvrow["' ,$fields);
// $linedata2 .= '$exporttocsvrow["'.$linedata1;
// $linedata3 .= $linedata2 .'"]';
// $linedatasplit = explode(",",$linedata3);
// $fieldsarrayforlinedata = array();
// foreach ($fields as $value) {
// array_push($fieldsarrayforlinedata , '$exporttocsvrow["'.$value.'"]');
// }
//output each row of the data, format line as csv and write to file pointer
while($exporttocsvrow = $exporttocsvresult->fetch_assoc()){
$fieldsarrayforlinedata = array_intersect_key($fields, $exporttocsvrow);
fputcsv($f, $fieldsarrayforlinedata, $delimiter);
}
//move back to beginning of file
fseek($f, 0);
//set headers to download file rather than displayed
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename="' . $safefilename . '";');
//output all remaining data on a file pointer
fpassthru($f);
I've left some commented out stuff in there that I replaced so you can 'see my working' as it were. I've currently got array_intersect_key in the loop that does each line of the CSV file, but I don't think that is the right answer, but I'm not sure what the name of what I'm trying to do is to Google it. The above code will currently result in just lots of blank cells in the csv where the data should be.
$fields contains the current list of fields I would like to export (Both the compulsory ones and the ones the user has ticked.) $fieldsarrayforlinedata is where I need to have the array of stuff for this one line of the CSV file from the $exporttocsvrow that is being looped over.
Does this make sense?