2013-04-27 136 views
54

我是一個新手程序員,我搜索了很多關於我的問題,但找不到有用的解決方案或有關此教程。如何從php腳本創建並下載csv文件?

我的目標是我有一個PHP數組和數組元素都出現在頁面上的列表中。

我想補充一個選項,這樣如果用戶想要的,他/她可以創建數組元素CSV文件並下載。

我不知道該怎麼做。我也搜索了很多。但還沒有找到有用的資源。

請給我一些教程或解決方案或建議,由我自己來實現它。由於我是新手,請提供易於實施的解決方案。

我的數組是這樣的:

Array 
(
    [0] => Array 
     (
      [fs_id] => 4c524d8abfc6ef3b201f489c 
      [name] => restaurant 
      [lat] => 40.702692 
      [lng] => -74.012869 
      [address] => new york 
      [postalCode] => 
      [city] => NEW YORK 
      [state] => ny 
      [business_type] => BBQ Joint 
      [url] => 
     ) 

) 
+2

phpExcel一個CSV文件是有點太much..http://php.net/manual/en/function。 fputcsv.php – 2013-04-27 11:39:33

+0

顯示您的數組結構,並提供一些代碼將元素轉換爲csv – 2013-04-27 11:43:54

+0

@半快我已經在帖子中添加了數組結構 – user2302780 2013-04-27 12:09:56

回答

122

您可以使用內置的fputcsv()你的陣列來生成與陣列正確的CSV行,所以你會在有循環和收集線。像:

$f = fopen("tmp.csv", "w"); 
foreach ($array as $line) { 
    fputcsv($f, $line) 
} 

爲了使瀏覽器提供的「另存爲」對話框中,您需要發送HTTP標頭是這樣的(見更多有關rfc這個頭):

header('Content-Disposition: attachment; filename="filename.csv";'); 

將所有內容一起:

function array_to_csv_download($array, $filename = "export.csv", $delimiter=";") { 
    // open raw memory as file so no temp files needed, you might run out of memory though 
    $f = fopen('php://memory', 'w'); 
    // loop over the input array 
    foreach ($array as $line) { 
     // generate csv lines from the inner arrays 
     fputcsv($f, $line, $delimiter); 
    } 
    // reset the file pointer to the start of the file 
    fseek($f, 0); 
    // tell the browser it's going to be a csv file 
    header('Content-Type: application/csv'); 
    // tell the browser we want to save it instead of displaying it 
    header('Content-Disposition: attachment; filename="'.$filename.'";'); 
    // make php send the generated csv lines to the browser 
    fpassthru($f); 
} 

而且你可以使用它像這樣:

array_to_csv_download(array(
    array(1,2,3,4), // this array is going to be the first row 
    array(1,2,3,4)), // this array is going to be the second row 
    "numbers.csv" 
); 

更新:
取而代之的php://memory您還可以使用php://output的文件描述符,並尋求與這樣做掉:

function array_to_csv_download($array, $filename = "export.csv", $delimiter=";") { 
    header('Content-Type: application/csv'); 
    header('Content-Disposition: attachment; filename="'.$filename.'";'); 

    // open the "output" stream 
    // see http://www.php.net/manual/en/wrappers.php.php#refsect2-wrappers.php-unknown-unknown-unknown-descriptioq 
    $f = fopen('php://output', 'w'); 

    foreach ($array as $line) { 
     fputcsv($f, $line, $delimiter); 
    } 
} 
+1

爲什麼不直接在迴路中「echo」生成的CSV行? – 2013-04-27 20:54:58

+1

@AlexShesterov,主要原因是'fputcsv()'不返回生成的行,它需要一個文件描述符來寫入。儘管如果你受到內存限制,你可以倒帶,寫,清除每次迭代的緩衝區。或者只是使用一個真正的臨時文件。 – complex857 2013-04-27 21:26:12

+0

@ complex857我如何爲csv添加列標題? – user2302780 2013-04-28 16:40:52

1

如果你的陣列結構永遠是多維中,準確的方式,那麼我們可以通過像這樣的元素:

$fh = fopen('somefile.csv', 'w') or die('Cannot open the file'); 

for($i=0; $i<count($arr); $i++){ 
    $str = implode(',', $arr[$i]); 
    fwrite($fh, $str); 
    fwrite($fh, "\n"); 
} 
fclose($fh); 

這是應該做的一種方式......你可以做手工,但這種方式是歸仁更容易理解和閱讀。

那麼你會管理你的頭的東西是什麼complex857做吐出的文件。如果您不再需要它,您可以使用unlink()刪除該文件,或者如果願意,可以將其保留在服務器上。

11

我沒有足夠的聲望回覆@ complex857解決方案。它很好用,但我不得不補充;在Content-Disposition標題的末尾。沒有它,瀏覽器會在文件名末尾添加兩個破折號(例如,代替「export.csv」,文件會保存爲「export.csv--」)。可能它會試圖在標題行末尾清理\ r \ n。

正確的路線應該是這樣的:

header('Content-Disposition: attachment;filename="'.$filename.'";'); 

在情況下,當CSV中有UTF-8字符,你必須改變的Content-Type行更改編碼設置爲UTF-8:

header('Content-Type: application/csv; charset=UTF-8'); 

另外,我覺得它更優雅的使用倒帶()代替FSEEK():

rewind($f); 

謝謝爲您的解決方案!

+2

我從來沒有在文件名末尾遇到'--',但是我已經更新了答案(爲什麼不提交一個編輯?) – complex857 2014-01-24 07:33:40

7
Try... 
csv download. 
<?php 
mysql_connect('hostname', 'username', 'password'); 
mysql_select_db('dbname'); 
$qry = mysql_query("SELECT * FROM tablename"); 
$data = ""; 
while($row = mysql_fetch_array($qry)) { 
    $data .= $row['field1'].",".$row['field2'].",".$row['field3'].",".$row['field4']."\n"; 
} 

header('Content-Type: application/csv'); 
header('Content-Disposition: attachment; filename="filename.csv"'); 
echo $data; exit(); 
?> 
3

使用下面的代碼的PHP數組轉換爲CSV

$ROW=db_export_data();//Will return a php array 
header("Content-type: application/csv"); 
header("Content-Disposition: attachment; filename=test.csv"); 
$fp = fopen('php://output', 'w'); 
$i=0; 
foreach ($ROW as $row) { 
fputcsv($fp, $row); 
$i++; 
} 
fclose($fp);