Search code examples
phpoutputarchivefputcsv

PHP output returning a tab space before write file


in this code I start with header to create a csv file:

    $cabecalho = array(
    "RazaoSocial",
    "NomeFantasia",
    "Nome",
    "CNPJ",
    "CPF",
    "Telefone",
    "E-Mail"
);
$cliente = array(
    "RazaoSocial" => "1",
    "NomeFantasia" => "2",
    "Nome" => "3",
    "CNPJ" => "4",
    "CPF" => "5",
    "Telefone" => "6",
    "EMail" => "7"
);

$clientes[] = $cliente;
/* Criando nome para o arquivo */
$filename = sprintf('lala_%s.csv', date('Y-m-d H-i'));


/* Definindo header de saída */
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header('Content-Description: File Transfer');
header("Content-type: text/csv; charset=utf-8", true);
header("Content-Disposition: attachment; filename={$filename}");
header("Expires: 0");
header("Pragma: public");

$fp = fopen('php://output', 'w');


fputcsv($fp, $cabecalho, ";");
foreach ($clientes as $val){
    fputcsv($fp, $val, ";");
}

fclose($fp);
exit();

when i save the file, returning a white space in init of archive, I don't have any idea. (img link);

image of archive

anyone has idea?


Solution

  • I found the solution:

    Create a temp file to write the data, create a new header, end buffer with not send the request, flush the archive and after all uses delete the temp file:

        define("PULAR_LINHA", "\n");
    define("DELIMITAR_COLUNA", ";");
    
        function writeArchive($fileName = "archive", $cabecalho = null, $valores = null){
    
        $filename = sprintf($fileName.'_%s.csv', date('Y-m-d H-i'));
    
        $tmpName = tempnam(sys_get_temp_dir(), 'data');
        $file = fopen($tmpName, 'w');
    
        fputcsv($file, $cabecalho, DELIMITAR_COLUNA);
        foreach ($valores as $val){
            fputcsv($file, $val, DELIMITAR_COLUNA);
        }       
        fclose($file);
    
        /* Abre uma chamada especifica somente para este arquivo temp */
        header('Content-Description: File Transfer');
        header('Content-Type: text/csv');
        header('Content-Disposition: attachment; filename='.$filename.'.csv');
        ob_end_clean(); //finalizar buffer sem enviar
        header('Content-Transfer-Encoding: binary');
        header('Expires: 0');
        header('Cache-Control: must-revalidate');
        header('Pragma: public');
        header('Content-Length: ' . filesize($tmpName));
    
        ob_clean();//finalizar buffer
        flush(); //descarregar o buffer acumulado
        readfile($tmpName); //ler arquivo/enviar
        unlink($tmpName); //deletar arquivo temporario
        exit();
    }