简体   繁体   English

从数组导出csv文件

[英]Export csv file from array

I am using below code for export multidimensional array. 我正在使用下面的代码导出多维数组。 I am using CodeIgniter framework(2.1.0 Version) 我正在使用CodeIgniter框架(2.1.0版)

Problems : 问题 :

  1. I have no any double quotes/single quotes in array but in csv file some fields have double quotes. 我在数组中没有任何双引号/单引号,但是在csv文件中某些字段具有双引号。

  2. Each and every csv file give me first two line blanks then contents I can see 每个csv文件都给我前两行空白,然后我可以看到的内容

CODE : 代码:

function array_to_csv($array, $download = "") {
    if ($download != "") {
        header('Content-Type: text/csv');
        header('Content-Disposition: attachement; filename="'.$download.
            '"');
        header("Pragma: no-cache");
        header("Expires: 0");
    }

    ob_start();
    $f = fopen('php://output', 'w') or show_error("Can't open php://output");
    $n = 0;
    foreach($array as $line) {
        $line = str_replace('"', '', $line); //Try to resolve first problem but it doesn't work for me.
        $n++;
        if (!fputcsv($f, $line)) {
            show_error("Can't write line $n: $line");
        }
    }
    fclose($f) or show_error("Can't close php://output");
    $str = ob_get_contents();
    ob_end_clean();

    if ($download == "") {
        return $str;
    } else {
        echo $str;
    }
}

try calling here: 尝试在这里致电:

$line = str_replace('"', '', $line)

trim function. 修剪功能。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM