I am trying to download a query as a .csv on a PHP web page, which has include_once ($_SERVER['DOCUMENT_ROOT'].'header.php');
at the top. When I use the PHP header()
function to download it, the .csv file contains the html code from header.php followed by the .csv data. How do I get the .csv without the html (only the query data)?
For downloading I use:
$query_file_name = "App_data.csv";
header("Content-type: text/csv");
header("Content-Disposition: attachment; filename=$query_file_name");
$query_file = fopen("php://temp", "w");
// write file
$row = $results->fetch_assoc();
fputcsv($query_file, array_keys($row)); // csv head
fputcsv($query_file, $row); // first line
while($row = $results->fetch_assoc()) {
fputcsv($query_file, $row);
}
fclose($query_file);
I realize I could trim the top of the file, but I do not know how to catch this before the file downloads. Optimally, I would only like to have the html from header.php not included at all.