我在MySQL数据库中有数据。我向用户发送一个URL,以获取他们的数据作为CSV文件。
我有链接的电子邮件,MySQL查询等覆盖。
当他们点击链接时,如何弹出从MySQL下载带有记录的CVS的窗口?
我已经有了所有能拿到唱片的资料。我只是不明白如何让PHP创建CSV文件,并让他们下载一个扩展名为. CSV的文件。
我在MySQL数据库中有数据。我向用户发送一个URL,以获取他们的数据作为CSV文件。
我有链接的电子邮件,MySQL查询等覆盖。
当他们点击链接时,如何弹出从MySQL下载带有记录的CVS的窗口?
我已经有了所有能拿到唱片的资料。我只是不明白如何让PHP创建CSV文件,并让他们下载一个扩展名为. CSV的文件。
当前回答
首先将data作为String,以逗号作为分隔符(用“,”分隔)。就像这样
$CSV_string="No,Date,Email,Sender Name,Sender Email \n"; //making string, So "\n" is used for newLine
$rand = rand(1,50); //Make a random int number between 1 to 50.
$file ="export/export".$rand.".csv"; //For avoiding cache in the client and on the server
//side it is recommended that the file name be different.
file_put_contents($file,$CSV_string);
/* Or try this code if $CSV_string is an array
fh =fopen($file, 'w');
fputcsv($fh , $CSV_string , "," , "\n" ); // "," is delimiter // "\n" is new line.
fclose($fh);
*/
其他回答
除了上述内容,你可能还需要补充:
header("Content-Transfer-Encoding: UTF-8");
它在处理包含多种语言的文件时非常有用,比如人名或城市。
<?
// Connect to database
$result = mysql_query("select id
from tablename
where shid=3");
list($DBshid) = mysql_fetch_row($result);
/***********************************
Write date to CSV file
***********************************/
$_file = 'show.csv';
$_fp = @fopen( $_file, 'wb' );
$result = mysql_query("select name,compname,job_title,email_add,phone,url from UserTables where id=3");
while (list( $Username, $Useremail_add, $Userphone, $Userurl) = mysql_fetch_row($result))
{
$_csv_data = $Username.','.$Useremail_add.','.$Userphone.','.$Userurl . "\n";
@fwrite( $_fp, $_csv_data);
}
@fclose( $_fp );
?>
Try:
header("Content-type: text/csv");
header("Content-Disposition: attachment; filename=file.csv");
header("Pragma: no-cache");
header("Expires: 0");
echo "record1,record2,record3\n";
die;
etc
编辑:这是我用来可选地编码CSV字段的代码片段:
function maybeEncodeCSVField($string) {
if(strpos($string, ',') !== false || strpos($string, '"') !== false || strpos($string, "\n") !== false) {
$string = '"' . str_replace('"', '""', $string) . '"';
}
return $string;
}
首先将data作为String,以逗号作为分隔符(用“,”分隔)。就像这样
$CSV_string="No,Date,Email,Sender Name,Sender Email \n"; //making string, So "\n" is used for newLine
$rand = rand(1,50); //Make a random int number between 1 to 50.
$file ="export/export".$rand.".csv"; //For avoiding cache in the client and on the server
//side it is recommended that the file name be different.
file_put_contents($file,$CSV_string);
/* Or try this code if $CSV_string is an array
fh =fopen($file, 'w');
fputcsv($fh , $CSV_string , "," , "\n" ); // "," is delimiter // "\n" is new line.
fclose($fh);
*/
创建您的文件,然后用正确的标题返回对它的引用,以触发另存为-根据需要编辑以下内容。将您的CSV数据放入$csvdata。
$fname = 'myCSV.csv';
$fp = fopen($fname,'wb');
fwrite($fp,$csvdata);
fclose($fp);
header('Content-type: application/csv');
header("Content-Disposition: inline; filename=".$fname);
readfile($fname);