我在MySQL数据库中有数据。我向用户发送一个URL,以获取他们的数据作为CSV文件。

我有链接的电子邮件,MySQL查询等覆盖。

当他们点击链接时,如何弹出从MySQL下载带有记录的CVS的窗口?

我已经有了所有能拿到唱片的资料。我只是不明白如何让PHP创建CSV文件,并让他们下载一个扩展名为. CSV的文件。


当前回答

<?
    // 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 );
?>

其他回答

我知道这个帖子有点老了,但作为将来的参考,以及像我这样的新手:

这里的其他人都解释了如何创建CSV,但忽略了问题的基本部分:如何链接。为了链接到CSV-file的下载,只需链接到.php-file,该文件将响应为. CSV-file。PHP头文件可以做到这一点。这可以实现一些很酷的东西,比如向查询字符串中添加变量并自定义输出:

<a href="my_csv_creator.php?user=23&amp;othervariable=true">Get CSV</a>

my_csv_creator.php可以使用查询字符串中给出的变量,例如使用不同的或自定义的数据库查询,更改CSV的列,个性化文件名等,例如:

User_John_Doe_10_Dec_11.csv

下面是一个使用PDO并包含列标题的完整工作示例:

$query = $pdo->prepare('SELECT * FROM test WHERE id=?');
$query->execute(array($id));    
$results = $query->fetchAll(PDO::FETCH_ASSOC);
download_csv_results($results, 'test.csv'); 
exit();


function download_csv_results($results, $name)
{            
    header('Content-Type: text/csv');
    header('Content-Disposition: attachment; filename='. $name);
    header('Pragma: no-cache');
    header("Expires: 0");

    $outstream = fopen("php://output", "wb");    
    fputcsv($outstream, array_keys($results[0]));

    foreach($results as $result)
    {
        fputcsv($outstream, $result);
    }

    fclose($outstream);
}

除了上述内容,你可能还需要补充:

header("Content-Transfer-Encoding: UTF-8");

它在处理包含多种语言的文件时非常有用,比如人名或城市。

编写自己的CSV代码可能是浪费你的时间,只是使用一个包,如league/ CSV -它为你处理所有困难的事情,文档是很好的,它是非常稳定/可靠的:

http://csv.thephpleague.com/

你需要使用作曲家。如果你不知道什么是作曲家,我强烈建议你去看看:https://getcomposer.org/

在$output变量中放入CSV数据,并返回正确的报头

header("Content-type: application/download\r\n");
header("Content-disposition: filename=filename.csv\r\n\r\n");
header("Content-Transfer-Encoding: ASCII\r\n");
header("Content-length: ".strlen($output)."\r\n");
echo $output;