Perl + Linux 檢測檔案是否為 UTF-8 與去除 BOM 方式

因為 UTF-8 有含 BOM 與不含 BOM 的格式,所以如果要處理一個 UTF-8 檔案需要先處理成一致格式再交給程式,以下是最近寫處理申請資料檔案時的相關程式碼.

  • 判別是否為 UTF-8 檔案主要是採用 Linux 內的 file 指令
  • 判別是否含有 BOM 的 UTF-8 是取檔案前兩個字元判別是否為 #0xef → 239 / #0xbb → 187,如果是就去掉.
:
:
	# 檢測 csv 是否為 UTF-8 格式
	$t_msg = `/usr/bin/file $p_regdir$p_csvfile`;
	if (index($t_msg, "UTF-8")<0) {
		$hash_logXMLInfo{'note'}="CSV File encoding is not UTF-8!";
		return((-1, "CSV File info:[$t_msg]", %hash_logXMLInfo));
	}
 
	$v_csvInfo = `/bin/cat $p_regdir$p_csvfile`;
	# 如果 csv 有函 BOM 的 UTF-8 則去掉前兩碼
	$t_chk1 = substr($v_csvInfo, 0, 1); #0xef -> 239
	$t_chk2 = substr($v_csvInfo, 1, 1); #0xbb -> 187
	if (ord($t_chk1)==239 && ord($t_chk2)==187) {
		$v_csvInfo = substr($v_csvInfo, 3);
	}
	# 讀取 csv 檔案內容 (支援 Unix \n 與 Dos \r\n 換行格式)
	@arr_csvLine = split(/\n|\r\n/,$v_csvInfo);
:
:
 
回到頁頂
tech/perl_check_utf8.txt · 上一次變更: 2008/04/28 12:08 來自 jonathan
chimeric.de = chi`s home Creative Commons License Valid CSS Driven by DokuWiki do yourself a favour and use a real browser - get firefox!! Recent changes RSS feed Valid XHTML 1.0