簡體   English   中英

使CSV文件可下載

[英]Make a CSV file Downloadable

我使用下面的代碼。 但是在tmp中創建的文件沒有下載。

 $error = fopen(/tmp/error.csv);
     $write[] = "hello";
     $dest_file_path="/tmp/error.csv";
        $dest_file_name="error.csv";
        if(!empty($write))
        {
            $flag = FALSE;
            fputcsv($error,$write,";");
            fclose($error);
            header("Content-Transfer-Encoding: Binary");
            header("Content-length: ".filesize($dest_file_path));
            header('Content-Type: text/csv');
            header('Content-Disposition: attachment; filename="'.$dest_file_name.'"');
            readfile($dest_file_path);
        }

該答案是按照您的原始帖子,而不將您編輯的帖子標記為“ edit ”。


問題是fopen()需要2個參數。

按照手冊:

<?php
$handle = fopen("c:\\folder\\resource.txt", "r");
?>

所以這行:

$error = fopen(/tmp/error.csv);

應該讀為(缺少引號,並且由於您要寫入文件w

$error = fopen('/tmp/error.csv', 'w');

您可能需要調整路徑,以達到以下目的:

$error = fopen('/var/user/you/tmp/error.csv', 'w');

要么

$error = fopen('/var/user/you/public_html/tmp/error.csv', 'w');

如果您有錯誤報告,則可能表示類似以下內容:

警告:fopen()至少需要2個參數,第1行的/path/to/file.php中給出1個參數

錯誤報告添加到文件頂部,這將有助於發現錯誤。

<?php 
error_reporting(E_ALL);
ini_set('display_errors', 1);

旁注:錯誤報告僅應在登台進行,而不應在生產過程中進行。


手冊中的更多示例:

<?php
$handle = fopen("/home/rasmus/file.txt", "r");
$handle = fopen("/home/rasmus/file.gif", "wb");
$handle = fopen("http://www.example.com/", "r");
$handle = fopen("ftp://user:password@example.com/somefile.txt", "w");
?>

試試這個代碼

// output headers so that the file is downloaded rather than displayed
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename=data.csv');

// create a file pointer connected to the output stream
$output = fopen('php://output', 'w');

// output the column headings
fputcsv($output, array('Column 1', 'Column 2', 'Column 3'));

// fetch the data
mysql_connect('localhost', 'username', 'password');
mysql_select_db('database');
$rows = mysql_query('SELECT field1,field2,field3 FROM table');

// loop over the rows, outputting them
while ($row = mysql_fetch_assoc($rows)) fputcsv($output, $row);

取自此鏈接http://code.stephenmorley.org/php/creating-downloadable-csv-files/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM