我在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);
*/

其他回答

首先将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);
*/
<?
    // 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 );
?>

〇简单的方法

$data = array (
    'aaa,bbb,ccc,dddd',
    '123,456,789',
    '"aaa","bbb"');

$fp = fopen('data.csv', 'wb');
foreach($data as $line){
    $val = explode(",",$line);
    fputcsv($fp, $val);
}
fclose($fp);

因此$data数组的每一行都将转到新创建的CSV文件的新行。它只适用于PHP 5及以后的版本。

创建您的文件,然后用正确的标题返回对它的引用,以触发另存为-根据需要编辑以下内容。将您的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);

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

http://csv.thephpleague.com/

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