225

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

我已经涵盖了链接、MySQL 查询等的电子邮件。

当他们单击链接时,我怎样才能弹出一个窗口来下载带有 MySQL 记录的 CVS?

我已经掌握了获取记录的所有信息。我只是不知道如何让 PHP 创建 CSV 文件并让他们下载扩展名为 .csv 的文件。

4

20 回答 20

477
header("Content-Type: text/csv");
header("Content-Disposition: attachment; filename=file.csv");

function outputCSV($data) {
  $output = fopen("php://output", "wb");
  foreach ($data as $row)
    fputcsv($output, $row); // here you can change delimiter/enclosure
  fclose($output);
}

outputCSV(array(
  array("name 1", "age 1", "city 1"),
  array("name 2", "age 2", "city 2"),
  array("name 3", "age 3", "city 3")
));

php://输出
fputcsv

于 2011-06-27T13:43:09.017 回答
292

尝试:

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;
}
于 2008-10-20T03:15:36.633 回答
19

这是@Andrew 发布的 php.net 函数的改进版本。

function download_csv_results($results, $name = NULL)
{
    if( ! $name)
    {
        $name = md5(uniqid() . microtime(TRUE) . mt_rand()). '.csv';
    }

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

    $outstream = fopen("php://output", "wb");

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

    fclose($outstream);
}

它真的很容易使用并且与 MySQL(i)/PDO 结果集一起工作得很好。

download_csv_results($results, 'your_name_here.csv');

exit()如果您完成了页面,请记住在调用它之后。

于 2012-02-14T19:07:00.847 回答
16

除了已经说过的所有内容之外,您可能还需要添加:

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

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

于 2013-03-14T23:32:07.090 回答
9

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

我知道,该线程有点旧,但供将来参考和像我一样的菜鸟:

这里的其他人都解释了如何创建 CSV,但错过了问题的一个基本部分:如何链接。为了链接到 CSV 文件的下载,您只需链接到 .php 文件,该文件又以 .csv 文件的形式响应。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
于 2011-12-10T09:07:05.733 回答
5

这是一个使用 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);
}
于 2013-07-01T18:05:14.743 回答
4

首先将数据制作为以逗号为分隔符的字符串(用“,”分隔)。像这样的东西

$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);
*/
于 2009-11-17T15:11:23.997 回答
3

嘿它工作得很好......!!!!感谢 Peter Mortensen 和 Connor Burton

<?php
header("Content-type: application/csv");
header("Content-Disposition: attachment; filename=file.csv");
header("Pragma: no-cache");
header("Expires: 0");

ini_set('display_errors',1);
$private=1;
error_reporting(E_ALL ^ E_NOTICE);

mysql_connect("localhost", "user", "pass") or die(mysql_error());
mysql_select_db("db") or die(mysql_error());

$start = $_GET["start"];
$end = $_GET["end"];

$query = "SELECT * FROM customers WHERE created>='{$start} 00:00:00'  AND created<='{$end} 23:59:59'   ORDER BY id";
$select_c = mysql_query($query) or die(mysql_error());

while ($row = mysql_fetch_array($select_c, MYSQL_ASSOC))
{
    $result.="{$row['email']},";
    $result.="\n";
    echo $result;
}

?>

于 2013-02-14T13:41:50.903 回答
3

您可以使用fputcsv函数简单地将数据写入 CSV 。让我们看看下面的例子。将列表数组写入 CSV 文件

$list[] = array("Cars", "Planes", "Ships");
$list[] = array("Car's2", "Planes2", "Ships2");
//define headers for CSV 
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename=file_name.csv');
//write data into CSV
$fp = fopen('php://output', 'wb');
//convert data to UTF-8 
fprintf($fp, chr(0xEF).chr(0xBB).chr(0xBF));
foreach ($list as $line) {
    fputcsv($fp, $line);
}
fclose($fp);
于 2015-03-06T07:53:26.893 回答
2

简单的方法 -

$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 及更高版本。

于 2010-02-12T09:39:39.840 回答
1

要让它以 CSV 格式发送并给出文件名,请使用 header():

http://us2.php.net/header

header('Content-type: text/csv');
header('Content-disposition: attachment; filename="myfile.csv"');

至于制作 CSV 本身,您只需遍历结果集,格式化输出并发送它,就像您处理任何其他内容一样。

于 2008-10-20T03:15:08.070 回答
1

代替:

$query = "SELECT * FROM customers WHERE created>='{$start} 00:00:00'  AND created<='{$end} 23:59:59'   ORDER BY id";
$select_c = mysql_query($query) or die(mysql_error()); 

while ($row = mysql_fetch_array($select_c, MYSQL_ASSOC))
{
    $result.="{$row['email']},";
    $result.="\n";
    echo $result;
}

采用:

$query = "SELECT * FROM customers WHERE created>='{$start} 00:00:00'  AND created<='{$end} 23:59:59'   ORDER BY id";
$select_c = mysql_query($query) or die(mysql_error()); 

while ($row = mysql_fetch_array($select_c, MYSQL_ASSOC))
{
    echo implode(",", $row)."\n";
}
于 2010-10-29T15:29:49.033 回答
1

最简单的方法是使用这样的专用CSV 类

$csv = new csv();
$csv->load_data(array(
    array('name'=>'John', 'age'=>35),
    array('name'=>'Adrian', 'age'=>23), 
    array('name'=>'William', 'age'=>57) 
));
$csv->send_file('age.csv'); 
于 2011-07-25T18:51:48.670 回答
1

已经非常好的解决方案来了。我只是在输入全部代码,以便新手获得全面帮助

<?php
extract($_GET); //you can send some parameter by query variable. I have sent table name in *table* variable

header("Content-type: text/csv");
header("Content-Disposition: attachment; filename=$table.csv");
header("Pragma: no-cache");
header("Expires: 0");

require_once("includes/functions.php"); //necessary mysql connection functions here

//first of all I'll get the column name to put title of csv file.
$query = "SHOW columns FROM $table";
$headers = mysql_query($query) or die(mysql_error());
$csv_head = array();
while ($row = mysql_fetch_array($headers, MYSQL_ASSOC))
{
    $csv_head[] =  $row['Field'];
}
echo implode(",", $csv_head)."\n";

//now I'll bring the data.
$query = "SELECT * FROM $table";
$select_c = mysql_query($query) or die(mysql_error()); 

while ($row = mysql_fetch_array($select_c, MYSQL_ASSOC))
{
    foreach ($row as $key => $value) {
            //there may be separator (here I have used comma) inside data. So need to put double quote around such data.
        if(strpos($value, ',') !== false || strpos($value, '"') !== false || strpos($value, "\n") !== false) {
            $row[$key] = '"' . str_replace('"', '""', $value) . '"';
        }
    }
    echo implode(",", $row)."\n";
}

?>

我已将此代码保存在 csv-download.php

现在看看我是如何使用这些数据下载 csv 文件的

<a href="csv-download.php?table=tbl_vfm"><img title="Download as Excel" src="images/Excel-logo.gif" alt="Download as Excel" /><a/>

因此,当我单击该链接时,它会下载文件,而不会将我带到浏览器上的 csv-download.php 页面。

于 2012-12-17T16:19:35.567 回答
0
<?
    // 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 );
?>
于 2008-12-11T19:55:34.937 回答
0

如何使用 PHP 脚本写入 CSV 文件?其实我也在找那个。使用 PHP 是一件容易的事。fputs(handler, content) - 这个函数对我来说很有效。首先,您需要使用 fopen($CSVFileName, 'wb') 打开需要写入内容的文件。

$CSVFileName = “test.csv”;
$fp = fopen($CSVFileName, ‘wb’);

//Multiple iterations to append the data using function fputs()
foreach ($csv_post as $temp)
{
    $line = “”;
    $line .= “Content 1″ . $comma . “$temp” . $comma . “Content 2″ . $comma . “16/10/2012″.$comma;
    $line .= “\n”;
    fputs($fp, $line);
}
于 2012-10-22T02:40:00.910 回答
0

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

http://csv.thephpleague.com/

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

于 2017-06-06T08:15:29.517 回答
0

公共函数 actionExportnotificationresponselogdata() {

    $fileName = '/tmp/notificationresponselogs_' . date('d-m-Y-g-i-h') . '.csv';
    $f = fopen($fileName, 'w'); 



        $csv_fields=array();
        $csv_fields[] = 'heading1';
        $csv_fields[] = 'heading2';
        $csv_fields[] = 'heading3';
        $csv_fields[] = 'heading4';
        $csv_fields[] = 'heading5';
        $csv_fields[] = 'heading6';
        $csv_fields[] = 'heading7';
        $csv_fields[] = 'heading8';
        fputcsv($f, $csv_fields);

    
$notification_log_arr = $notificationObj->getNotificationResponseForExport($params); //result from database

    if (count($notification_log_arr) > 0) {
        $serialNumber=1;
    foreach ($notification_log_arr AS $notifaction) {
            

            $fields = array();
            $fields['serialNumber']= $serialNumber  ;
            $fields['fld_1']= $notifaction['fld_1'] ;
            $fields['fld_2']= $notifaction['fld_2'] ;
            $fields['fld_3']= $notifaction['fld_3'] ;
            $fields['fld_4']= $notifaction['fld_4'] ;
            $fields['fld_5']= $notifaction['fld_5'] ;
            $fields['fld_6']= $notifaction['fld_6'] ; 
            $fields['fld_7']= $notifaction['fld_7'] ; 
           // print_r($fields); die;
            fputcsv($f, $fields,",");
        
            $serialNumber++;  }
            fclose($f);
            if (file_exists($fileName)) {
                
                header("Content-type: application/csv");
                header("Content-Disposition: attachment; filename="."exportlog".date("Y-m-d_H:i").".csv");
                header("Content-length: " . filesize($fileName));
                header("Pragma: no-cache"); 
                header("Expires: 0");
                readfile($fileName);
                unlink($fileName);
                exit;
            }
}
于 2022-03-04T05:58:46.400 回答
-1

将 CSV 数据放入$output变量并使用正确的标题回显

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;
于 2010-11-18T10:57:27.540 回答