我有一个记录一些信息的 .txt 文件。我想将它加载到 MySQL 表中,但我有以下问题:.txt 日志文件不统一,这意味着它看起来像这样:
04092012 16:07:34.988 stuff1 stuff2 username1 importantStuff
04092012 16:08:12.145 stuff1 stuff2 stuff3 username2 stuff4 importantStuff
重要的是所有用户名都以相同的字符开头,就像这里一样。我知道我应该使用类似的东西:
$lines=file(log.txt);
foreach($lines as $v) {
$values = explode(' ',$v);
...
但我不知道如何将日期、时间、用户名和importantStuff 转移到MySQL 表中。
我很感激能得到的任何帮助。提前致谢。
最佳答案
$file = file_get_contents('log.txt');
$lines = explode("\n", $file);
foreach($lines as $v) {
$values = explode(' ',$v);
$all = count($values);
$user = preg_match_all('/(user\w+\b)/', $v, $matches); // it will match all usernames that start with "user"
$time = $values[1];
$username = $matches[0][0];
$stuff = $values[($all-1)];
$date = $values[0];
$query = "INSERT INTO `MyTable` ('".$date."', '".$time."', '".$username."', '".$stuff."')";
}
关于php - 使用php仅将txt文件中的某些行加载到mysql表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12265383/