2009-10-29 115 views
7

假設我已經將查詢存儲在名爲$ query的變量中。我想在結果頁面上創建一個名爲「以CSV格式導出」的小超鏈接。我該怎麼做呢?通過PHP將查詢結果導出爲CSV

回答

11
$query = "SELECT * FROM table_name"; 

$export = mysql_query ($query) or die ("Sql error : " . mysql_error()); 

$fields = mysql_num_fields ($export); 

for ($i = 0; $i < $fields; $i++) 
{ 
    $header .= mysql_field_name($export , $i) . "\t"; 
} 

while($row = mysql_fetch_row($export)) 
{ 
    $line = ''; 
    foreach($row as $value) 
    {            
     if ((!isset($value)) || ($value == "")) 
     { 
      $value = "\t"; 
     } 
     else 
     { 
      $value = str_replace('"' , '""' , $value); 
      $value = '"' . $value . '"' . "\t"; 
     } 
     $line .= $value; 
    } 
    $data .= trim($line) . "\n"; 
} 
$data = str_replace("\r" , "" , $data); 

if ($data == "") 
{ 
    $data = "\n(0) Records Found!\n";       
} 

header("Content-type: application/octet-stream"); 
header("Content-Disposition: attachment; filename=your_desired_name.xls"); 
header("Pragma: no-cache"); 
header("Expires: 0"); 
print "$header\n$data"; 
+0

ArneRie和您的答案組合完美無缺 – Arc 2009-11-04 11:28:56

5

ehm?

<a href="yourexport.php" title="export as csv">Export as CSV</a> 

,如果你正在尋找腳本至極可以這樣做:

$myArray = array(); 

$fp = fopen('export.csv', 'w'); 

foreach ($myArray as $line) { 
    fputcsv($fp, split(',', $line)); 
} 

fclose($fp); 
+0

注意:fputcsv只適用於PHP5。 – Raptor 2009-10-29 08:25:18

+0

拆分已棄用... – Raja 2013-03-26 13:25:38

3

CSV =逗號分隔值=用逗號

你有迴音/打印結果線分開你的價值觀按行分隔,用逗號(,)分隔。

我假設你的$查詢結果集查詢,這是一個關聯數組:

while($query = mysql_fetch_assoc($rs)) { 
    // loop till the end of records 
    echo $query["field1"] . "," . $query["field2"] . "," . $query["field3"] . "\r\n"; 
} 

其中$ RS是資源句柄。

讓瀏覽器彈出一個下載框,你必須在文件的開頭設置頁眉(假設你的文件名是export.csv):

header("Expires: 0"); 
header("Cache-control: private"); 
header("Cache-Control: must-revalidate, post-check=0, pre-check=0"); 
header("Content-Description: File Transfer"); 
header("Content-Type: application/vnd.ms-excel"); 
header("Content-disposition: attachment; filename=export.csv"); 

這就是它!

p.s.這種方法不會在服務器中留下物理文件。如果您打算在服務器中生成文件,請使用傳統的fopen和fwrite函數。