繁体   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