1 <?php 2 header("content-type:text/html; charset=utf-8"); 3 echo "导入纯真ip库"; 4 $conn = mysql_connect('localhost', 'root', 'password') or 5 die("Could not connect: " . mysql_error()); 6 mysql_select_db("database"); 7 mysql_query("set names utf8"); 8 9 //解析ip.txt数据, 并插入数据库中 10 set_time_limit(-1); 11 $file = "/path/to/ip.txt"; 12 $fp = fopen($file, "r"); 13 while($str = trim(fgets($fp, 2000))){ 14 preg_match("/([\.\d]+)\s+([\.\d]+)\s+(.*?)\s+(.*)/is", $str, $arr); 15 unset($arr[0]); 16 $arr = array_map("my_replace", $arr); 17 $str = iconv("gbk", "utf-8", 18 "INSERT INTO `ip`(`ip_start`,`ip_end`,`area`,`position`) 19 VALUES('".implode("','", $arr)."');\n"); 20 mysql_query($str); 21 } 22 fclose($fp); 23 24 //function start 25 function my_replace($str) { 26 return str_replace("'", "''", $str); 27 } 28 29 ?>