如何使用 php 从文本文件中排除第一行
How to exclude the first line from a text file using php
我的文本文件 sample.txt。我想从文本文件中排除第一行并将其他行存储到 mysql 数据库中。
ID Name EMail
1 Siva xyz@gmail.com
2 vinoth xxx@gmail.com
3 ashwin yyy@gmail.com
现在我想从文本文件中读取除第一行(ID、姓名、电子邮件)之外的这些数据并存储到 MYsql db.Because 我已经在数据库中创建了一个文件同名
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.
请告诉我该怎么做?
谢谢。
问候,
湿婆
如果使用 file() 会更容易,因为它会获取数组中的所有行:
// 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);
Note: As @Don'tPanic pointed out in his comment, using file()
is simple and easy but not advisable if the original file is large, since it will read the whole thing into memory as an array (and arrays take more memory than strings). He also correctly recommended the FILE_IGNORE_NEW_LINES-flag, just so you know :-)
您只需在 while 循环之前调用 fgets
一次即可将 header 行移开。
$firstline = fgets($handle, 4096);
while (!feof($handle)) // Loop till end of file.
{ ...
我的文本文件 sample.txt。我想从文本文件中排除第一行并将其他行存储到 mysql 数据库中。
ID Name EMail
1 Siva xyz@gmail.com
2 vinoth xxx@gmail.com
3 ashwin yyy@gmail.com
现在我想从文本文件中读取除第一行(ID、姓名、电子邮件)之外的这些数据并存储到 MYsql db.Because 我已经在数据库中创建了一个文件同名
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.
请告诉我该怎么做?
谢谢。 问候, 湿婆
如果使用 file() 会更容易,因为它会获取数组中的所有行:
// 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);
Note: As @Don'tPanic pointed out in his comment, using
file()
is simple and easy but not advisable if the original file is large, since it will read the whole thing into memory as an array (and arrays take more memory than strings). He also correctly recommended the FILE_IGNORE_NEW_LINES-flag, just so you know :-)
您只需在 while 循环之前调用 fgets
一次即可将 header 行移开。
$firstline = fgets($handle, 4096);
while (!feof($handle)) // Loop till end of file.
{ ...