程序员最近都爱上了这个网站  程序员们快来瞅瞅吧!  it98k网:it98k.com

本站消息

站长简介/公众号

  出租广告位,需要合作请联系站长

+关注
已关注

分类  

暂无分类

标签  

暂无标签

日期归档  

暂无数据

如何从php脚本创建和下载csv文件?

发布于2021-03-11 10:01     阅读(546)     评论(0)     点赞(2)     收藏(1)


我是一名新手程序员,我搜索了很多有关我的问题的内容,但找不到与此有关的有用解决方案或教程。

我的目标是我有一个PHP数组,并且数组元素显示在页面上的列表中。

我想添加一个选项,以便用户如果愿意,他/她可以创建带有数组元素的CSV文件并下载。

我不知道该怎么做。我也搜索了很多。但尚未找到任何有用的资源。

请为我提供一些教程或解决方案或建议以自己实施。由于我是新手,请提供易于实施的解决方案。

我的数组看起来像:

Array
(
    [0] => Array
        (
            [fs_id] => 4c524d8abfc6ef3b201f489c
            [name] => restaurant
            [lat] => 40.702692
            [lng] => -74.012869
            [address] => new york
            [postalCode] => 
            [city] => NEW YORK
            [state] => ny
            [business_type] => BBQ Joint
            [url] => 
        )

)

解决方案


您可以为数组使用内置的fputcsv()从数组中生成正确的csv行,因此,您必须循环并收集行,如下所示:

$f = fopen("tmp.csv", "w");
foreach ($array as $line) {
    fputcsv($f, $line);
}

为了使浏览器提供“另存为”对话框,您将必须发送如下的HTTP标头(有关更多信息,请参见rfc):

header('Content-Disposition: attachment; filename="filename.csv";');

放在一起:

function array_to_csv_download($array, $filename = "export.csv", $delimiter=";") {
    // open raw memory as file so no temp files needed, you might run out of memory though
    $f = fopen('php://memory', 'w'); 
    // loop over the input array
    foreach ($array as $line) { 
        // generate csv lines from the inner arrays
        fputcsv($f, $line, $delimiter); 
    }
    // reset the file pointer to the start of the file
    fseek($f, 0);
    // tell the browser it's going to be a csv file
    header('Content-Type: application/csv');
    // tell the browser we want to save it instead of displaying it
    header('Content-Disposition: attachment; filename="'.$filename.'";');
    // make php send the generated csv lines to the browser
    fpassthru($f);
}

您可以像这样使用它:

array_to_csv_download(array(
  array(1,2,3,4), // this array is going to be the first row
  array(1,2,3,4)), // this array is going to be the second row
  "numbers.csv"
);

更新:
代替,php://memory您还可以将php://output用作文件描述符,并取消查找等:

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


所属网站分类: 技术文章 > 问答

作者:黑洞官方问答小能手

链接:http://www.phpheidong.com/blog/article/1465/ac51a9d8043ef8b0da02/

来源:php黑洞网

任何形式的转载都请注明出处,如有侵权 一经发现 必将追究其法律责任

2 0
收藏该文
已收藏

评论内容:(最多支持255个字符)