I am trying to convert a php/mysql generated table into a downloadable csv file. When a user enters search parameters, a call is made to a mysql table and results returned as table.
I used the solution offered in this thread and it works fabulously: Create a CSV File for a user in PHP
I am able to allow users to save or view the results as a csv file. the problem I am having is I'm not sure how to add column headers to the file. For example, the results that are returned are in the following format: $result[x]['office'], $result[x]['user'], etc..., but I also want to add column titles like "Office" and "User" so that anyone looking at the csv file immediately knows what the data means.
This is the function that generates the csv file:
header("Content-type: text/csv");
header("Content-Disposition: attachment; filename=$file.csv");
header("Pragma: no-cache");
header("Expires: 0");
outputCSV($data);
function outputCSV($data) {
$outstream = fopen("php://output", "a");
function __outputCSV(&$vals, $key, $filehandler) {
fputcsv($filehandler, $vals); // add parameters if you want
}
array_walk($data, "__outputCSV", $outstream);
fclose($outstream);
}
I have tried creating the following function, and then calling it right before I call outputCSV, but it is not successful:
function create_file_header()
{
$headers = 'Office, User, Tag, Value';
$fp = fopen("php://output", "w");
file_put_contents("$file.csv", $headers);
fclose($fp);
}
Any help is greatly appreciated.