php将文本文件中的数据插入到mysql中

时间:2013-02-04 09:03:09

标签: php mysql

我有一个文本文件logfile.txt:

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 个答案:

答案 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
}

答案 1 :(得分: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);
}