[php] 讀 CSV 檔

if ( empty($_SERVER["DOCUMENT_ROOT"]) ) $DOC_ROOT="/m1/root";
else $DOC_ROOT=$_SERVER["DOCUMENT_ROOT"];

include $DOC_ROOT."/db.inc.php";

$filename="test_data.dat";
$filename="d_0416.dat";
$max_aline=1000;

if ( !$__db_mysql=@mysql_connect($__config['host'],$__config['user'],$__config['pass'],FALSE, MYSQL_CLIENT_COMPRESS) ) {
  debug_log($process_log,"fail on connect db,0");
  die('fail on connect db,0');
}

mysql_select_db('demo',$__db_mysql);
mysql_query("set names big5", $__db_mysql);

setlocale(LC_ALL,'zh_TW.Big5');
$fp=fopen($filename,"r");

$cnt=0;
while ( $data=fgetcsv($fp,1000) ) {
  if ( count($data)!=48 ) continue;

  unset( $f_name );
  unset( $f_data );
  $f_data[]=0;
  foreach ($data as $k => $v) {
    $f_name[]="f_".$k;
    $f_data[]=sprintf("'%s'",substr($v,0,200));
  }
  $f_data[]=time();

  $sql=sprintf("insert into user2 values (%s)",implode(',',$f_data));
  printf("%d\n",$cnt);
  $result=mysql_query($sql, $__db_mysql);

  $cnt++;
}
fclose($fp);

mysql_close($__db_mysql);

// —–
function xdisp($data) {
  global $fp;
  $data=fgetcsv($fp,1000);
  printf("%d\n",count($data));
  print_r($data);
}