修正原有fgetcsv中文亂碼問題。
1.先將getcsv重寫,參考一下程式碼(測試可用)
/**
* fgetcsv
*
* 修正原生fgetcsv讀取中文函式
*
* @param CSV文件檔案
* @param length 每一行所讀取的最大資料長度
* @param d 資料分隔符號(預設為逗號)
* @param e 字串包含符號(預設為雙引號)
* @return $_csv_data
PHP 4 使用 fgetcsv
PHP 5 使用 str_getcsv
*/
function str_getcsv(&$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;
}
1.匯入CSV
<?php
$dbname="test.csv";
$fp = fopen("$dbname","r");
$size = filesize($dbname);
$row=1;
while($temp=str_getcsv($fp,$size,",")){
if ($row>0){
setlocale(LC_ALL,"cht");
echo $temp[2]."<br>";
$sql="INSERT INTO subscribe (test1,test2,test3) VALUES ('test1','test2,'test3'')";
$result=mysql_query($sql);
echo mysql_error();
}
$row=$row+1;
}
fclose($fp);
?>
沒有留言:
張貼留言