这是我想将数据转换为csv格式并下载的问题 . 一切都很好,直到我下载的csv文件和文件的一个小错误,文件的第一行会有一个空格 .
例如强制下载之前
"name","age",
"brad pit","40",`
强行下载后
"name","age",
"brad pit","40",
我下载的csv文件和我尝试用excel打开的机器将会显示如下
"name" |年龄
布拉德坑| 40
我相信这是因为我下载的csv文件在数据的第一行出现了外部空格行 .
这是代码
//write csv data
$data = $this->dbutil->csv_from_result($query, $delimiter);
//create random file name
$name = rand().'_salesperson_data_'.date('d-m-y').'.csv';
if ( ! write_file('./csv/'.$name, $data))
{
echo 'Unable to write the CSV file';
}
else
{
//perform download
$file = file_get_contents("./csv/".$name); // Read the file's contents
$filename = 'salesperson_data_'.date('d-m-y').'.csv';
force_download($filename, $file);
}
force_download()的来源
if ( ! function_exists('force_download'))
{
function force_download($filename = '', $data = '')
{
if ($filename == '' OR $data == '')
{
return FALSE;
}
// Try to determine if the filename includes a file extension.
// We need it in order to set the MIME type
if (FALSE === strpos($filename, '.'))
{
return FALSE;
}
// Grab the file extension
$x = explode('.', $filename);
$extension = end($x);
// Load the mime types
@include(APPPATH.'config/mimes'.EXT);
// Set a default mime if we can't find it
if ( ! isset($mimes[$extension]))
{
$mime = 'application/octet-stream';
}
else
{
$mime = (is_array($mimes[$extension])) ? $mimes[$extension][0] : $mimes[$extension];
}
// Generate the server headers
if (strstr($_SERVER['HTTP_USER_AGENT'], "MSIE"))
{
header('Content-Type: "'.$mime.'"');
header('Content-Disposition: attachment; filename="'.$filename.'"');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header("Content-Transfer-Encoding: binary");
header('Pragma: public');
header("Content-Length: ".strlen($data));
}
else
{
header('Content-Type: "'.$mime.'"');
header('Content-Disposition: attachment; filename="'.$filename.'"');
header("Content-Transfer-Encoding: binary");
header('Expires: 0');
header('Pragma: no-cache');
header("Content-Length: ".strlen($data));
}
exit($data);
}
}
我认为TRIM将是我的最后一个解决方案,我试图尽可能地放置任何东西,但是同样如此 . 我找不到解决这个问题的方法 . 请帮忙 . 这已经困扰了我2天了 .
提前致谢 .
3 回答
尝试在浏览器上打印,如果你看到一些额外的空间,然后删除 .
如果在下载时额外仍在csv文件中,则此额外空间来自您的任何包含文件 .
当你开始编写代码时,尽量不要在代码的顶部/底部留出一些空间 .
在写入CSV之前使用
ob_clean();
删除空格 .我不知道是否只需要使用CSV,但我使用的插件/功能就是这个:http://codeigniter.com/wiki/Excel_Plugin/
它适用于CodeIgniter查询系统,用于将内容导出到Excel . 我经常使用它,从来没有遇到任何问题 .