2013-02-04 224 views
-1

我有一個文本文件LOGFILE.TXT:PHP插入數據到mysql

2013-01-01 12:01:00 ip:11223344 region: country:US bandwidth:123 
2013-01-01 12:01:55 ip:22222 region: country:UK bandwidth:123 
2013-01-01 12:03:12 ip:34566 region: country:US bandwidth:123 
2013-01-01 12:07:08 ip:123123 region: country:US bandwidth:123 

我怎樣才能把它插入到MySQL,這些列:

ID  | IP_client | country | bandwidth 
+2

使用爆炸()首先爆炸機智h空格而不是: – rohitarora

+1

是CSV嗎?給出一些關於文件的更多細節 –

+0

可能重複http://stackoverflow.com/questions/4729031/how-do-i-read-this-text-file-and-insert-into-mysql – Rikesh

回答

3
$text = file_get_contents('file.txt'); 
$text = explode("\n",$text); 
foreach($text as $line) 
{ 
$temp = explode('ip:',$line); 
$ip = explode(" ",$temp[1]); 

$temp = explode('country:',$line); 
$country = explode(" ",$temp[1]); 

$temp = explode('bandwidth:',$line); 
$bandwidth = explode(" ",$temp[1]); 


$sql = "INSERT INTO MY_TABLE (IP_client,country,bandwidth) VALUES ('".$ip[0]."','".$country[0]."','".$bandwidth[0]."')"; 
mysql_query($sql); 
} 
+0

你應該接受答案,如果它幫助你 –

3

可以使用類似的代碼,它的一個選項卡分離器:

$data = file_get_contents("file.txt"); 
$convert = explode("\n", $data); //create array separate by new line 
for ($i=0;$i<count($convert);$i++) 
{ 
    //insert record here 
}