filepointer: previously opened file pointer array(fields) : The data array delimiter : by default it is comma ( , ) , you can change to a new one enclosure : One character can be used to enclose data
From array to CSV file
We will use one multidimensional array and then use the same data to store in a csv file by using fputcsv function.
We will modify file header and post the csv file to the browser so user can download it and save in the local computer.
Here is the code with modified header to force file download in user computer .
<?Php
require "config.php"; // Database Connetion
$sql= "SELECT * from student ";
if(strlen($sql) <6){echo "No Query ";
exit;
}
$filename='student.csv';
header( 'Content-Type: text/csv' );
header( 'Content-Disposition: attachment;filename='.$filename);
$fp = fopen('php://output', 'w');
$STH = $dbo->prepare($sql);
$STH->execute();
$first_row = $STH->fetch(PDO::FETCH_ASSOC);
$headers = array_keys($first_row);
$headers = array_map('ucfirst', $headers); // optional, capitalize first letter of headers
fputcsv($fp, $headers); // put the headers
fputcsv($fp, array_values($first_row)); // put the first row
while ($row = $STH->fetch(PDO::FETCH_NUM)) {
fputcsv($fp,$row); // push the rest
}
fclose($fp);
?>
Note the way we are opening the file. When we are storing the visitor details we have to add one line each time a new visitor details are to be stored. When we are storing the student records we are opening the file and storing all data in one go and then closing it.