我正在嘗試用 php 撰寫一個 CSV 檔案。我已經嘗試了 Stack Overflow 上給出的許多示例,但是當我在 Open Office 或 Notepad 中打開我的 CSV 檔案時,它們都將換行符 \n 顯示為文本而不是換行符。例如,數字 id 的串列如下所示:
編號\n1\n2\n3\n4\n5\n6\n7\n8\n9\n10\n11\n12\n13\n15\n16\n17\n18\n
我嘗試在 id 字串周圍加上引號,但這只是輸出:
"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);
uj5u.com熱心網友回復:
你\n是單引號的。嘗試雙引號:“\n”。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/445965.html
