Search code examples
phpcodeigniter

Writing a CSV File New Line Characters Showing as Text


I'm trying to write a CSV file with php. I've tried many examples given on Stack Overflow but when I open my CSV file in Open Office or Notepad++ they both show the newline \n as text instead of a new line. For example, a list of numerical ids comes out as:

id\n1\n2\n3\n4\n5\n6\n7\n8\n9\n10\n11\n12\n13\n15\n16\n17\n18\n

I tried putting quotes around the id string but that just outputted:

"id"\n1\n2\n3\n4\n5\n6\n7\n8\n9\n10\n11\n12\n13\n15\n16\n17\n18\n

How do I get a line break? I've also tried \r\n, and I tried adding a line of code to specify the encoding, which was suggested in another post, but that just added as text as well. Any help is appreciated, thanks!

Code to make CSV string:

    //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;
    }

Code to write to file:

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

Solution

  • Your \n are single quoted. Try double quotes: "\n".