在PHP中为用户创build一个CSV文件

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

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

我怎么能当他们点击链接时,popup一个下载带有MySQLlogging的CVS?

我已经获得了所有的信息。 我只是看不到如何让PHP创buildCSV文件,让他们下载一个.csv扩展名的文件。

尝试:

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; 

等等

编辑:这是我用来select编码CSV字段的一段代码:

 function maybeEncodeCSVField($string) { if(strpos($string, ',') !== false || strpos($string, '"') !== false || strpos($string, "\n") !== false) { $string = '"' . str_replace('"', '""', $string) . '"'; } return $string; } 
 header("Content-Type: text/csv"); header("Content-Disposition: attachment; filename=file.csv"); function outputCSV($data) { $output = fopen("php://output", "w"); 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

这里是@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", "w"); foreach($results as $result) { fputcsv($outstream, $result); } fclose($outstream); } 

MySQL(i)/ PDO结果集使用起来非常简单,效果很好。

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

如果您完成了该页面,请记得在调用此函数后exit()

除了所有已经提到的,你可能需要添加:

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

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

我知道这个线程有点老,但是为了将来的参考,以及作为我自己的noobs,

这里的其他人解释如何创buildCSV,但错过了一个基本的部分:如何链接。 为了链接到CSV文件的下载,您只需链接到.php文件,该文件反过来又是.csv文件。 PHP头文件就是这样做的。 这使得很酷的东西,如添加variables到查询string和自定义输出:

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

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

 User_John_Doe_10_Dec_11.csv 

创build你的文件,然后用正确的头返回一个引用,以触发另存为 – 根据需要编辑以下内容。 把你的CSV数据放入$ csvdata。

 $fname = 'myCSV.csv'; $fp = fopen($fname,'w'); fwrite($fp,$csvdata); fclose($fp); header('Content-type: application/csv'); header("Content-Disposition: inline; filename=".$fname); readfile($fname); 

这是一个使用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", "w"); fputcsv($outstream, array_keys($results[0])); foreach($results as $result) { fputcsv($outstream, $result); } fclose($outstream); } 

首先使用逗号作为分隔符(用“,”分隔)将数据作为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); */ 

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

?>

简单的方法 –

 $data = array ( 'aaa,bbb,ccc,dddd', '123,456,789', '"aaa","bbb"'); $fp = fopen('data.csv', 'w'); foreach($data as $line){ $val = explode(",",$line); fputcsv($fp, $val); } fclose($fp); 

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

您可以简单地使用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', 'w'); //convert data to UTF-8 fprintf($fp, chr(0xEF).chr(0xBB).chr(0xBF)); foreach ($list as $line) { fputcsv($fp, $line); } fclose($fp); 

最简单的方法是使用这样的专用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'); 

代替:

 $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"; } 

已经非常好的解决scheme来了。 我只是把总代码,以便新手得到全面的帮助

 <?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页面。

要把它作为一个CSV发送,并给它的文件名,使用header():

http://us2.php.net/header

 header('Content-type: text/csv'); header('Content-disposition: attachment; filename="myfile.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, 'w' ); $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 ); ?> 

这是我之前完成的,在特定date之间抓取数据。 希望它有帮助。

 <?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; } ?> 

如何使用PHP脚本在CSV文件中写入? 其实我也在寻找这个。 使用PHP是一件容易的事情。 fputs(处理程序,内容) – 这个函数对我有效。 首先,您需要使用fopen($ CSVFileName,'w')打开您需要编写内容的文件。

 $CSVFileName = “test.csv”; $fp = fopen($CSVFileName, 'w'); //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); } 

编写自己的CSV代码可能是浪费你的时间,只需使用一个软件包,如联盟/ csv – 它处理所有困难的东西,文件是好的,它是非常稳定/可靠的:

http://csv.thephpleague.com/

你需要使用composer php。 如果你不知道composer php是什么,我强烈build议你看看: https : //getcomposer.org/

$outputvariables中放入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;