我正在尝试用php写一个CSV文件。我已经尝试了很多关于Stack Overflow的例子,但是当我在Open Office或Notepad++中打开CSV文件时,它们都将换行符显示为文本而不是新行。例如,一个数字id列表显示为:
识别码\n1\n2\n3\n4\n5\n6\n7\n8\n9\n10\n11\n12\n13\n15\n16\n17\n18\n
我试着在id字符串周围加上引号,但结果只是输出:
“识别码”\n1\n2\n3\n4\n5\n6\n7\n8\n9\n10\n11\n12\n13\n15\n16\n17\n18\n
我如何获得换行符?我也尝试过\r\n,我尝试添加一行代码来指定编码,这是另一篇文章中建议的,但也只是作为文本添加。任何帮助都是感谢的,谢谢!
生成CSV字符串的代码:
//format array to be written to CSV
public function data_to_csv($data, $headers = TRUE) {
if ( ! is_array($data)) {
return 'invalid Data provided';
}
$CSVText="";
$array = array();
if ($headers) {
$array2 = get_object_vars($data[0]);
$properties = array_keys($array2);
$CSVText.=implode(',', $properties).'\n';
}
foreach ($data as $row) {
$array = get_object_vars($row);
$properties = array_values($array);
$CSVText.=implode(',',$properties).'\n';
}
return $CSVText;
}
要写入档案的程式码:
require_once(APPPATH.'libraries/pclzip/pclzip.lib.php');
$rand=random_string('alnum',16);
$created=FALSE;
while (!$created){
if(!is_dir($this->config->item('temp_path').$rand)) {
mkdir($this->config->item('temp_path').$rand,0755);
$dir=$this->config->item('temp_path').$rand;
$created=TRUE;
}
}
$programDataCSV = $this->extractor_model->data_to_csv($programData['data'], true);
$zipPath=$this->config->item('temp_path')."$rand/search_results_data.zip";
$zip= new PclZip($zipPath);
$programPath=$this->config->item('temp_path')."$rand/programs.csv";
if ($programData['resultCount']>0){
//open filestream for program data
$program_handle=fopen($programPath,'a');
if (!$program_handle){
show_error('could not open hand for program data');
}
fwrite($program_handle,$programDataCSV);
fclose($program_handle);
$zip->add($programPath,PCLZIP_OPT_REMOVE_PATH,$this->config->item('temp_path').$rand);
}
$data=file_get_contents($zipPath);
$this->load->helper('download');
$this->load->helper("file");
delete_files($this->config->item('temp_path').$rand);
rmdir($this->config->item('temp_path').$rand);
force_download('search_results_data.zip',$data);
1条答案
按热度按时间m1m5dgzv1#
您的
\n
是单引号。请尝试使用双引号:“\n”。