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



在此代码中,我从标头开始创建一个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 of archive 中返回一个空格,我一无所知。(图片链接(;

档案图片

有人知道吗?

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

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

ob_end_clean();

标头((之前的代码;问题就解决了。

我找到了解决方案

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

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

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

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

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

最新更新