简体   繁体   中英

Export to CSV PHP as a Download File

I am using a CSV file to export a mysql table. How can I view it as a download file now that it is stored on Drive C: directly without any notification

<?php
$host = 'localhost'; // <--  db address
$user = 'root'; // <-- db user name
$pass = 'root'; // <-- password
$db = 'urs'; // db's name
$table = 'veiwresult'; // table you want to export
$file = 'alaa'; // csv name.
$link = mysql_connect($host, $user, $pass) or die("Can not connect." . mysql_error());
mysql_select_db($db) or die("Can not connect.");
$result = mysql_query(" SELECT ApplicantNum,name, averg,choice FROM veiwresult");
fputcsv($f, array('ApplicantNum','name','averg', 'choice'));
$timestamp = date('Ymd-His'); 

$f = fopen("C:/mycsv-{$timestamp}.csv", 'w');
// Headers    
while($row = mysql_fetch_row($result))
{
fputcsv($f, $row);
}


fputcsv($f, $items_array);
fclose($f);

?>

If you want to store csv-file and then open it without any clicking, it`s impossible.

If you just wish to have it opened, open it in browser window via

header('Content-disposition: inline;filename=foobar.csv');
header('Content-Type: text/csv;charset=UTF-8');
echo $csv_content;

where $csv_content is a string with contents of csv-file. You cat get it this way

$csv_content = file_get_contents('c:/mycsv.csv');

To download it...

<?php
$host = 'localhost'; // <--  db address
$user = 'root'; // <-- db user name
$pass = 'root'; // <-- password
$db = 'urs'; // db's name
$table = 'veiwresult'; // table you want to export
$file = 'alaa'; // csv name.
$link = mysql_connect($host, $user, $pass) or die("Can not connect." . mysql_error());
mysql_select_db($db) or die("Can not connect.");
$result = mysql_query(" SELECT ApplicantNum,name, averg,choice FROM veiwresult");
fputcsv($f, array('ApplicantNum','name','averg', 'choice'));
$timestamp = date('Ymd-His'); 

$f = fopen("C:/mycsv-{$timestamp}.csv", 'w');
// Headers    
while($row = mysql_fetch_row($result))
{
fputcsv($f, $row);
}

fputcsv($f, $items_array);
fclose($f);

header('Content-type: application/csv');
header('Content-Disposition: attachment; filename="mycsv-{$timestamp}"');
readfile('C:/mycsv-{$timestamp}.csv');
?>

This will still notify the user of the download, and depending on their settings they may need to accept the download. This functionality cannot be overridden of course.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM