2009-10-29 13 views

答えて

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

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

+0

splitは非推奨です... – Raja

3

CSVを=コンマ区切り値=あなたが/エコーあなたの結果の行を印刷する必要があり

コンマ

で自分の価値観を分離カンマ(、)で区切って行単位で入力します。

私はあなたの$クエリが連想配列でクエリの結果セット、であると仮定:$ RSはリソースハンドルです

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

。ブラウザがダウンロードボックスをポップアップし、あなたはファイルの先頭にヘッダーを設定しなければならないようにする

(ファイル名を想定しているた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関数を使用します。

関連する問題