1

I'm trying to write a csv file from an array, as a header of a csv file

$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);

All the file is correct except a hidden character at the beginning of the file. If I open the file with notepad it display correctly, but in Excel there is a blank line at the beginning. Can anyone help me?

4

3 回答 3

6

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

例子:

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

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

于 2019-08-26T13:32:28.940 回答
4

我觉得很好。我用

$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);
于 2013-11-23T23:29:28.100 回答
0

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

如何在 PHP 中输​​出 Excel 可以正确读取的 UTF-8 CSV?

查看最受好评的解决方案,它回显结果而不是写入临时文件。它是这样的:

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);
于 2013-11-23T23:27:08.407 回答