用 PHP 为用户创建一个 CSV 文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/217424/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 21:57:41  来源:igfitidea点击:

Create a CSV File for a user in PHP

phpcsvdownloadhttp-headers

提问by Oleg Barshay

I have data in a MySQL database. I am sending the user a URL to get their data out as a CSV file.

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

I have the e-mailing of the link, MySQL query, etc. covered.

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

How can I, when they click the link, have a pop-up to download a CVS with the record from MySQL?

当他们单击链接时,我如何才能弹出一个从 MySQL 下载带有记录的 CVS?

I have all the information to get the record already. I just don't see how to have PHP create the CSV file and let them download a file with a .csv extension.

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

回答by Andrii Nemchenko

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://output
fputcsv

php://输出
fputcsv

回答by Oleg Barshay

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

等等

Edit: Here's a snippet of code I use to optionally encode CSV fields:

编辑:这是我用来选择对 CSV 字段进行编码的代码片段:

function maybeEncodeCSVField($string) {
    if(strpos($string, ',') !== false || strpos($string, '"') !== false || strpos($string, "\n") !== false) {
        $string = '"' . str_replace('"', '""', $string) . '"';
    }
    return $string;
}

回答by Xeoncross

Here is an improved version of the function from php.net that @Andrew posted.

这是@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);
}

It is really easy to use and works great with MySQL(i)/PDO result sets.

它真的很容易使用并且非常适合 MySQL(i)/PDO 结果集。

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

Remember to exit()after calling this if you are done with the page.

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

回答by Stan

In addition to all already said, you might need to add:

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

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

It's very useful when handling files with multiple languages in them, like people's names, or cities.

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

回答by LBJ

The thread is a little old, I know, but for future reference and for noobs as myself:

我知道该线程有点旧,但供将来参考和我自己的菜鸟使用:

Everyone else here explain how to create the CSV, but miss a basic part of the question: how to link. In order to link to download of the CSV-file, you just link to the .php-file, which in turn responds as being a .csv-file. The PHP headers do that. This enables cool stuff, like adding variables to the querystring and customize the output:

这里的其他人都解释了如何创建 CSV,但错过了问题的一个基本部分:如何链接。为了链接到 CSV 文件的下载,您只需链接到 .php 文件,该文件又作为 .csv 文件响应。PHP 标头就是这样做的。这可以实现很酷的东西,比如向查询字符串添加变量并自定义输出:

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

my_csv_creator.php can work with the variables given in the querystring and for example use different or customized database queries, change the columns of the CSV, personalize the filename and so on, e.g.:

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

User_John_Doe_10_Dec_11.csv

回答by typemismatch

Create your file then return a reference to it with the correct header to trigger the Save As - edit the following as needed. Put your CSV data into $csvdata.

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

回答by Justin

Here is a full working example using PDO and including column headers:

这是一个使用 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);
}

回答by Behzad Ravanbakhsh

First make data as a String with comma as the delimiter (separated with ","). Something like this

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

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

回答by Kaddy

Hey It works very well....!!!! Thanks Peter Mortensen and Connor Burton

嘿它运作得很好....!!!! 感谢 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;
}

?>

?>

回答by user244641

Simple method -

简单的方法——

$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);

So each line of the $dataarray will go to a new line of your newly created CSV file. It only works only for PHP 5 and later.

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