簡體   English   中英

CSV下載

[英]CSV to Download

我的HTML:

<h2>Download Example CSV - IN DEVELOPMENT (not working yet)</h2><br />
<form method="post" enctype="multipart/form-data">
<input type="submit" name="example-csv" value="Download Example" />
</form>

我的PHP:

function array_to_csv_download($array, $filename = "example.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);
    }
    fclose($f);
}

if(isset($_POST['example-csv'])) {
    $data = array (
                array('column_1', 'column_2', 'column_3'),
                array('test 1', 'test 2', 'test 3',)
    );
    array_to_csv_download($data);
}

怎么了:

當我單擊“下載示例”提交按鈕時,它會給我一個文件example.csv。 該文件幾乎是我當前頁面上的所有代碼,包括所有javascript,HTML以及發送到瀏覽器的所有其他內容。

我可以ctrl + F在混亂中找到我想要的實際數據。

我的問題:

為什么我要獲取頁面的所有代碼,而不僅僅是我要查找的簡單CSV?

用來達到我目的的資源:

如何從php腳本創建和下載csv文件?

在表單提交時調用特定的PHP函數

最后說明:

我根據自己的需要調整了上面的資源,但似乎無法獲得我想要的東西。 我希望這足夠詳細。 請根據需要進行澄清。

謝謝。

問題很簡單,您必須在fclose之后添加出口死掉 ,然后在文件數據之后將不再提供html代碼。

我不確定您的文件結構是什么,但這應該是這樣

您的HTML文件:

<h2>Download Example CSV - IN DEVELOPMENT (not working yet)</h2><br />
<form method="post" action="ServeFile.php" enctype="multipart/form-data">
<input type="submit" name="example-csv" value="Download Example" />
</form>

PHP文件ServerFile.php:這是您放在上面的PHP文件,只需確保在<?php and at the end.. (simply omit php closing tag ?> )之前<?php and at the end.. (simply omit php closing tag ?> )沒有空格<?php and at the end.. (simply omit php closing tag ?> )

由於您要發送標頭(header(..)),因此在發送標頭之前不應發送任何輸出,即使是空格,因此該文件必須是單獨的PHP文件。

暫無
暫無

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

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