如何使用php从文本文件中排除第一行
我的文本文件sample.txt。我想从文本文件中排除第一行,并将其他行存储到mysql数据库中如何使用php从文本文件中排除第一行,php,mysql,text-files,fopen,fgets,Php,Mysql,Text Files,Fopen,Fgets,我的文本文件sample.txt。我想从文本文件中排除第一行,并将其他行存储到mysql数据库中 ID Name EMail 1 Siva xyz@gmail.com 2 vinoth xxx@gmail.com 3 ashwin yyy@gmail.com 现在我想从文本文件中读取这些数据,除了第一行(ID、名称、电子邮件),并将其存储到MYsql数据库中,因为我已经在数据库中创建了一个同名的文件 I have tried $handle = @fopen($filename, "r
ID Name EMail
1 Siva xyz@gmail.com
2 vinoth xxx@gmail.com
3 ashwin yyy@gmail.com
现在我想从文本文件中读取这些数据,除了第一行(ID、名称、电子邮件),并将其存储到MYsql数据库中,因为我已经在数据库中创建了一个同名的文件
I have tried
$handle = @fopen($filename, "r"); //read line one by one
while (!feof($handle)) // Loop till end of file.
{
$buffer = fgets($handle, 4096); // Read a line.
}
print_r($buffer); // It shows all the text.
请告诉我怎么做
谢谢。
当做
湿婆R如果使用,则更容易,因为它将取而代之地获取数组中的所有行:
// Get all rows in an array (and tell file not to include the trailing new lines
$rows = file($filename, FILE_IGNORE_NEW_LINES);
// Remove the first element (first row) from the array
array_shift($rows);
// Now do what you want with the rest
foreach ($rows as $lineNumber => $row) {
// do something cool with the row data
}
如果您想再次将其作为字符串,而不使用第一行,只需使用新行作为胶水将其内爆:
// The rows still contain the line break, since we only trimmed the copy
$content = implode("\n", $rows);
注意:正如@Don'tPanic在他的评论中指出的那样,使用file()
简单易行,但如果原始文件较大,则不建议使用方法,因为它将整个内容作为数组读入内存(数组占用的内存比字符串多)。他还正确地推荐了文件\u IGNORE\u NEW\u LINES-flag,正如您所知:-)
如果使用,则更容易,因为它将取而代之地获取数组中的所有行:
// Get all rows in an array (and tell file not to include the trailing new lines
$rows = file($filename, FILE_IGNORE_NEW_LINES);
// Remove the first element (first row) from the array
array_shift($rows);
// Now do what you want with the rest
foreach ($rows as $lineNumber => $row) {
// do something cool with the row data
}
如果您想再次将其作为字符串,而不使用第一行,只需使用新行作为胶水将其内爆:
// The rows still contain the line break, since we only trimmed the copy
$content = implode("\n", $rows);
注意:正如@Don'tPanic在他的评论中指出的那样,使用file()
简单易行,但如果原始文件较大,则不建议使用方法,因为它将整个内容作为数组读入内存(数组占用的内存比字符串多)。他还正确地推荐了文件\u IGNORE\u NEW\u LINES-flag,正如您所知:-)
您只需在while循环之前调用一次
fgets
,以避开标题行
$firstline = fgets($handle, 4096);
while (!feof($handle)) // Loop till end of file.
{ ...
您只需在while循环之前调用一次
fgets
,以避开标题行
$firstline = fgets($handle, 4096);
while (!feof($handle)) // Loop till end of file.
{ ...
看起来,
$buffer
应该只保留while循环之后的最后一行。看起来,$buffer
应该只保留while循环之后的最后一行。我同意文件
很方便,尽管如果文件很大,可能最好不要一次读取整个文件。(看起来你的数组\u shift
,顺便说一句。)@Don'tPanic-是的,在大文件中使用它是愚蠢的。最好指出这一点。我不知道文件\u IGNORE\u NEW\u行
-标志。干杯隐马尔可夫模型。。我可能是瞎子,但我看不到打字错误?我同意文件
很方便,尽管如果文件很大,可能最好不要一次读完整个文件。(看起来你的数组\u shift
,顺便说一句。)@Don'tPanic-是的,在大文件中使用它是愚蠢的。最好指出这一点。我不知道文件\u IGNORE\u NEW\u行
-标志。干杯隐马尔可夫模型。。我可能是瞎的,但我看不到打字错误?