Glad To Help
Glad To Help

Reputation: 5387

Codeigniter's csv_from_result() not working with UTF-8 characters?

I have some data which is in Cyrilic and I wanted to export it in .csv file with Codeigniter. The problem is that the method csv_from_result() messes those characters.

$this->load->dbutil();
$delimiter = ",";
$newline = "\r\n";

$report_result =  $this->data_model->get_data_result();
$data['csv']    = $this->dbutil->csv_from_result($report_result, $delimiter, $newline);

And in my view I have:

<?php
header("Content-type: application/csv-tab-delimited-table; charset=utf-8" );
header("Content-Disposition: attachment; filename=csvdata.csv" );
header("Content-Transfer-Encoding: binary" );
  echo $csv; 
?> 

The output file, contains messed characters like these:

ТеÑÑ‚ пиÑмо","54","Референц

Upvotes: 1

Views: 6156

Answers (3)

Prog Mania
Prog Mania

Reputation: 624

csv_from_result from ci generates utf-8 without BOM, and you can find the difference here so all you need to do now is to convert "utf-8 without BOM" to "utf-8", and you can do it with the following code.

$this->load->dbutil();
$delimiter = ",";
$newline = "\r\n";

$report_result =  $this->data_model->get_data_result();
$CSV_data      = $this->dbutil->csv_from_result($report_result, $delimiter, $newline);
$CSV_data = chr(239) . chr(187) . chr(191) .$CSV_data;
$data['csv'] = $CSV_data;

Upvotes: 5

Glad To Help
Glad To Help

Reputation: 5387

I ended up using PHPExcel for Codeigniter . That worked like a charm.

Upvotes: 1

csotelo
csotelo

Reputation: 1485

Try this:

$this->load->dbutil();
$query = $this->db->query($sql);
$delimiter = ",";
$newline = "\r\n";

header ("Content-disposition: attachment; filename=csvoutput_" . time() . ".csv") ;
echo mb_convert_encoding($this->dbutil->csv_from_result($query, $delimiter, $newline), "ISO-8859-1", "UTF-8");

Upvotes: 0

Related Questions