在php中写入csv文件时,开头为空行


Blank line at the beginning when writing a csv file in php

我正试图从数组中写入一个csv文件,作为csv文件的标头

$csv_fields[] = 'produto_quest';
$csv_fields[] = 'produto_quest1';
$csv_fields[] = 'comentario_aspecto_atm';
$csv_fields[] = 'aspecto_geral_int';
$csv_fields[] = 'organizacao_espaco';
$f = fopen('php://memory', 'w+');
fputcsv($f, $csv_fields, ";");
foreach ($relat as $fields) { // load from MySQL as a multidimensional array
    foreach($fields as $key => &$value1) {
        $value1 = iconv("UTF-8", "", $value1);
    }
    fputcsv($f, $fields, ";");
}
fseek($f, 0);
fpassthru($f);
fclose($f);

除了文件开头的一个隐藏字符外,所有文件都是正确的。如果我用记事本打开文件,它会正确显示,但在Excel中,开头有一行空白。有人能帮我吗?

$f = fopen('php://memory', 'w+'); 之前使用ob_clean();

示例:

ob_clean();
$f = fopen('php://memory', 'w+');

删除CSV文件开头的所有空行对我来说效果很好。

我觉得不错。我用测试过

$relat = array(range(1,5), range(3,7));

我没有空白或隐藏的字符:

HTTP/1.1 200 OK
Date: Sat, 23 Nov 2013 23:26:27 GMT
Server: Apache/2.4.6 (Ubuntu)
X-Powered-By: PHP/5.5.3-1ubuntu2
Vary: Accept-Encoding
Content-Length: 109
Content-Type: text/html
produto_quest;produto_quest1;comentario_aspecto_atm;aspecto_geral_int;organizacao_espaco
1;2;3;4;5
3;4;5;6;7

更新:由于这种情况只发生在您身上,而不会发生在其他人身上,我相信这是因为您的php源文件中有一些换行符。确保标记之外没有任何内容,比如之前文件开头的换行符

您可以通过调用来测试这是否是问题的原因

ob_end_clean();

之前

fpassthru($f);

这里已经讨论了类似的问题:

如何在PHP中输出一个UTF-8 CSV,以便Excel正确读取?

看看投票最多的解决方案,它会回显结果,而不是写入临时文件。它是这样的:

header('Content-Encoding: UTF-8');
header('Content-type: text/csv; charset=UTF-8');
header('Content-Disposition: attachment; filename=Customers_Export.csv');
echo "'xEF'xBB'xBF"; // UTF-8 BOM
echo $csv_file_content;

更新:

header('Content-Encoding: UTF-8');
header('Content-type: text/csv; charset=UTF-8');
header('Content-Disposition: attachment; filename=Customers_Export.csv');
echo "'xEF'xBB'xBF"; // UTF-8 BOM
$csv_fields[] = 'produto_quest';
$csv_fields[] = 'produto_quest1';
$csv_fields[] = 'comentario_aspecto_atm';
$csv_fields[] = 'aspecto_geral_int';
$csv_fields[] = 'organizacao_espaco';
$f = fopen('php://memory', 'w+');
fputcsv($f, $csv_fields, ";");
foreach ($relat as $fields) { // load from MySQL as a multidimensional array
    foreach($fields as $key => &$value1) {
        $value1 = iconv("UTF-8", "", $value1);
    }
    fputcsv($f, $fields, ";");
}
fseek($f, 0);
fpassthru($f);
fclose($f);