I’m exporting a some data from a survey to CSV for use by another team with PHP. I have outputted my first row of data as all of the headings. But I need some of the headings to span 2 columns is the at all possible.
The headings are all in correctly, but I need to add two cells of data underneath some of the headings.
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename=lite-survey-data_'.time().'.csv');
require_once ( dirname(dirname(dirname(dirname(__FILE__)))).'/wp-load.php' );
$content =build_csv_download();
$headings = convert_to_csv($content[0]);
$csv_content = convert_to_csv($content[1]);
$output = fopen('php://output', 'w');
fwrite($output, $headings);
fwrite($output, $csv_content);
Any ideas?
CSV does not support column spanning. Some programs like Excel might try to make sense out of missing headings or other such tricks, but that doesn’t leave you with a valid CSV file. See https://www.rfc-editor.org/rfc/rfc4180
Concatenate the data with a non-significant string (like a space or a hyphen) before making the CSV data. Basically, you’re just taking the two data columns and making them in to one.
The easiest way to do this is to use
CONCAT(docs) to combine the stings right out of the database:If you can’t do that in the database query, you can use
array_walk(docs) to do it after the fact: