PHP 输出在写入文件前返回一个制表符 space

PHP output returning a tab space before write file

在这段代码中,我从 header 开始创建一个 csv 文件:

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

当我保存文件时,在存档的初始化中返回白色 space,我不知道。 (img link);

image of archive

有人知道吗?

我找到了解决方案:

创建一个临时文件来写入数据,创建一个新的 header,结束缓冲区而不发送请求,刷新存档并在所有使用后删除临时文件:

    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();
}

我遇到了同样的问题,我的输出文件总是以制表符 space 开头。

解决方案更简单,我添加了

ob_end_clean();

header()之前的代码;问题就解决了。

请尝试将此 csv 文件保存在磁盘上,保存后您可以直接下载此文件或重定向

header('Location: http://www.example.com/newfile.csv');

在将此文件保存到磁盘时,您也会发现实际问题。