It's me ;-)

Export to CSV file with Unicode

Ở bài trước tôi có đề cập đến việc export dữ liệu ra file CSV. Tuy nhiên, nếu export dữ liệu có chứa các ký tự Unicode thì sẽ không hiển thị được mặc dù khi mở bằng Notepad thì vẫn hiển thị đúng, tuy nhiên khi mở bằng Excel thì không hiển thị chính xác. Search trên mạng thấy giải pháp của anh Nguyễn Văn Hùng (Hưng?) đã giải quyết được (tôi mới test với German characters trong dự án Shop24 – rất okie).

Bài toán: export dữ liệu tiếng Việt UTF-8 thành file CSV có thể hiển thị đúng khi mở bằng Excel.
3 điểm dẫn đến thành công:
+ Dùng TAB (\t) thay cho COMMA (,) để phân tách các cột
+ Convert Encoding của dữ liệu cần output bằng UTF-16LE
+ Gắn chr(255)chr(254) vào đầu của kết quả cuối cùng trước khi output

PHP code đầy đủ (export order list):

/**
 * EXPORT ORDER LIST TO CSV FILE
 * @author khanhdn
 */
function exportCSV() {
	global $user;
	member_access();

	$memberInfo = member_info();

	$result = drupal_query("SELECT order_id
					,order_code
					,bill_firstname
					,bill_lastname
					,order_modify_date
					,gand_total
					,order_status
					 FROM {order}
					 WHERE shop_code = '".$memberInfo['shop_code']."'
					 ORDER BY order_creation_date DESC");

	$status_options = array(
                                '1'  => 'Neu'
				,'2' => 'In Bearbeitung'
				,'3' => 'Auf der Post'
				,'4' => 'Ausgeführt'
				,'5' => 'Zurück'
				);

	$csv = "Order code\tCustomer Name\tModify Date\tOrder Total\tOrder Status\r\n";

	if(count($result['data']))
	{
		foreach($result['data'] as $row)
		{
			$order_list = array(
							'order_code' 		=> "$row->order_code"
							,'customer_name' 	=> $row->bill_firstname. ' ' .$row->bill_lastname
							,'modify_date' 		=> mysqlTimestamp(strtotime($row->order_modify_date),'d.m.Y')
							,'order_total'		 => 'CHF '.$row->gand_total
							,'order_status'		=> $status_options[$row->order_status]
			);

			$csv .= join("\t", $order_list)."\r\n";
		}

	}
	$csv = chr(255).chr(254).mb_convert_encoding($csv, "UTF-16LE", "UTF-8");

	header("Content-type: application/x-msdownload");
	header("Content-disposition: csv; filename=" . date("Y-m-d") .
	"_order_list.csv; size=".strlen($csv));
	echo $csv;
	exit();
}

Source: Nguyễn Văn Hùng weblog

4 thoughts on “Export to CSV file with Unicode

  1. Thanks for entry, nhưng chưa thấy nói đến giải pháp import lại từ UTF-16LE. khoai quá!

  2. Bạn thử dùng mb_convert_encoding để chuyển lại encoding xem sao? Cái này tớ cũng chỉ làm theo hướng dẫn của anh Hưng (tác giả bài viết này) thôi 🙂

  3. Hi all,
    Hiện mình đang muốn làm import file excel mà nội dung trong file là chữ có dấu,minh import vô mysql được rồi nhưng khi móc lên thì nó bị bể font,không biết bạn nào đã làm như vây chưa hướng dẫn mình với.Minh muốn sau khi import vao db,rồi lại đọc ra và export ra file xml.Minh lam duoc het roi nhung den cai cho bể font,gio ko biet lma sao.hix

Leave a Reply to Phat Nhac.Com Cancel reply

Your email address will not be published. Required fields are marked *