天天看點

linux下,fgetcsv亂碼問題

今日使用fgetcsv()函數導入CSV檔案,在本地測試無問題,但傳到伺服器(linux)上則會出現漢字亂碼問題,花了好久時間,在網上找到了解決辦法,大概有兩種:

1、使用PHP自定義處理.csv檔案的函數:

// http://www.todo8.com/?m=20090519

/**

 * 對CSV進行處理

 * @param resource handle

 * @param int length

 * @param string delimiter

 * @param string enclosure

 * @return 檔案内容或FALSE。

 */

 function __fgetcsv(& $handle, $length = null, $d = ‘,’, $e = ‘”‘) {

     $d = preg_quote($d);

     $e = preg_quote($e);

     $_line = “”;

     $eof=false;

     while ($eof != true) {

         $_line .= (empty ($length) ? fgets($handle) : fgets($handle, $length));

         $itemcnt = preg_match_all(’/’ . $e . ‘/’, $_line, $dummy);

         if ($itemcnt % 2 == 0)

             $eof = true;

     }

     $_csv_line = preg_replace(’/(?: |[ ])?$/’, $d, trim($_line));

     $_csv_pattern = ‘/(’ . $e . ‘[^' . $e . ']*(?:’ . $e . $e . ‘[^' . $e . ']*)*’ . $e . ‘|[^' . $d . ']*)’ . $d . ‘/’;

     preg_match_all($_csv_pattern, $_csv_line, $_csv_matches);

     $_csv_data = $_csv_matches[1];

     for ($_csv_i = 0; $_csv_i < count($_csv_data); $_csv_i++) {

         $_csv_data[$_csv_i] = preg_replace(’/^’ . $e . ‘(.*)’ . $e . ‘$/s’, ‘$1′, $_csv_data[$_csv_i]);

         $_csv_data[$_csv_i] = str_replace($e . $e, $e, $_csv_data[$_csv_i]);

     return empty ($_line) ? false : $_csv_data;

 }

2、使用: setlocale 函數設定環境變量。:

// from: http://hi.baidu.com/getpost/blog/item/762132f94889c85f252df2bd.html

設定setlocale(LC_ALL,'zh_CN');

做項目涉及到繁體的文檔,就整個簡體繁體都加上,應該影響不會很大:setlocale(LC_ALL,'zh_HK','zh_TW','zh_CN');

試了下第2個方法,好似可行,不過現在連不上伺服器,是以并沒确定