PHP输出在写入文件之前返回选项卡空间

时间:2018-05-04 12:54:13

标签: php output archive fputcsv

在这段代码中我从头开始创建一个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();

当我保存文件,在存档的init中返回一个空格时,我什么都不知道。 (img link);

image of archive

有人有想法吗?

3 个答案:

答案 0 :(得分:0)

我找到了解决方案

创建临时文件以写入数据,创建新标头,结束缓冲区但不发送请求,刷新存档并在所有使用后删除临时文件:

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

答案 1 :(得分:0)

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

我补充说,解决方案要简单得多

{{1}}

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

答案 2 :(得分:0)

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

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

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