I've trauled through this site and found tonnes of threads about this same thing but none really help a complete novice like me as I dont understand the answers properly.
I have selected data from a database and displayed in a table on a webpage. I now need a link below this table which will export this data to a CSV file.
one of the answers I have found on this site is: Create a CSV File for a user in PHP
However the answer doesnt really make sense to me and I dont know what to do with the code.
Here is the code from that answer:
header("Content-type: text/csv");
header("Content-Disposition: attachment; filename=file.csv");
header("Pragma: no-cache");
header("Expires: 0");
$array = array(
array("data11", "data12", "data13"),
array("data21", "data22", "data23"),
array("data31", "data32", "data23"));
outputCSV($array);
function outputCSV($data) {
$outstream = fopen("php://output", "w");
function __outputCSV(&$vals, $key, $filehandler) {
fputcsv($filehandler, $vals); // add parameters if you want
}
array_walk($data, "__outputCSV", $outstream);
fclose($outstream);
}
I have so many questions like do I need to create an excel file first? if so does it need to be blank?
what is this?:
$array = array(
array("data11", "data12", "data13"),
array("data21", "data22", "data23"),
array("data31", "data32", "data23"));
is this supposed to be my data? how do I change that to suit the data I have?
Why is the call to the function before the function is defined?
what are these variables in the function ($vals, $key, $filehandler) and where are they created?
How do I use this code because so many people seem to think its perfect.
I really need help from start to finish with this as I am a complete PHP novice
Ive worked on one of the answers below and now I have this code
$i=0;
$csv="";
for ($a=0; $a<=$count; $a++) {
$i++;
$csv.=preg_replace("/
/",'',preg_replace("/,/",';',$serveys[$a]['FeedbackName'])).",".
preg_replace("/
/",'',preg_replace("/,/",';',$serveys[$a]['BranchName']));
$csv.="
";
}
if ($i>0) {
header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: private",false);
header("Content-Type: application/octet-stream");
header("Content-Disposition: attachment; filename=\"table.csv\";" );
header("Content-Transfer-Encoding: binary");
echo $csv;
} else {
return "Nothing to download!";
}
when I run the page though there is no change, the data is still displayed on the page as it should be. but no csv file is created and no errors occurr