Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

php

csv

fputcsv

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?

like image 927
RBrazao Avatar asked Sep 05 '25 03:09

RBrazao


1 Answers

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

Example:

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

It works fine for me to remove all blank lines at the begining of the CSV file.

like image 84
Silambarasan R.D Avatar answered Sep 07 '25 22:09

Silambarasan R.D