I am a beginner student of PHP and i am doing some practice by coding a script to generate a CSV file. Once that the csv file is generated , the format is correct as I've expected : See the attached :
But if i add the download option the csv is generated wrongly with all the PHP page (i can see all the code)
Here the picture of the wrong csv
Could you help me to find the issue ?
Here the code :
<?php
include("db.php");
session_start();
$sql = "SELECT isocode FROM test_geo ORDER BY isocode";
$result_csv = mysqli_query($conn, $sql);
//facebook csv creation //
$filename = 'test.csv';
$fp = fopen($filename, 'w');
$headers = ['key', 'country'];
fputcsv($fp, $headers);
foreach ($result_csv as $key => $id) {
$new = array_push($id, "country");
fputcsv($fp, $id);
var_dump($id);
}
fclose($fp);
?>
CodePudding user response:
Try this
header("Content-type: text/csv");
header("Content-Disposition: attachment; filename=result_file.csv");
header("Pragma: no-cache");
header("Expires: 0");
$output = fopen("php://output", "w");
foreach ($new as $row) {
fputcsv($outputt, $row);
}
fclose($outputt);
exit();
CodePudding user response:
I believe you put the header statements at the top of your script, so the download data includes the HTML codes too (like below...)
<!DOCTYPE html><html lang="en"><meta charset=...... >
You may use ob_flush() and set header (at the appropriate position of the code) so that the file will be correctly downloaded as csv when it is generated.
Here is the code:
<?php
session_start();
include("db.php");
$sql = "SELECT isocode FROM test_geo ORDER BY isocode";
$result_csv = mysqli_query($conn, $sql);
$data=array();
while($row = mysqli_fetch_array($result_csv, MYSQLI_ASSOC)) {
$ok=$row["isocode"] . "," . "Country";
array_push($data ,$ok);
}
ob_flush();
$filename="ok1.csv";
$csvData = join("\n", $data);
header('Content-Disposition: attachment; filename="'.$filename.'";');
header('Content-Type: application/csv; charset=UTF-8');
die($csvData);
?>