如何使用PHP删除txt中的前两行

时间:2018-11-13 19:34:26

标签: php

例如,我有数据:

File generated by system automatically...
9 rows selected.

Heber,Camrynborough,26728,Home Health Aide
Modesto,West Janet,15152-2683,Software Engineer
Dante,East Chanel,74689-6886,Entertainment Attendant
Nolan,Murphyville,32561-8079,Credit Authorizer
Jovany,O'Reillyton,44371,Medical Assistant
Jaeden,Greenfort,06179-1759,School Social Worker
Efrain,West Blairborough,11282-0496,Electronic Drafter
Travon,South Tatum,76603-0822,Manufactured Building Installer
Agustina,North Gertrudeland,18950,Health Services Manager

和简单的php代码将数据导入mysql

$open = fopen('employee-data.txt','r');

while (!feof($open)) 
{
    $getTextLine = fgets($open);
    $explodeLine = explode(",",$getTextLine);

    list($name,$city,$postcode,$job_title) = $explodeLine;

    $qry = "insert into empoyee_details (name, city,postcode,job_title) values('".$name."','".$city."','".$postcode."','".$job_title."')";
    mysqli_query($conn,$qry);
}

fclose($open);

它可以正常工作,但是开始读取文件时出现问题,因为文件包含三行无用的行(两行带有文本,最后一行为空)。在开始将数据导入mysql之前如何删除行?

2 个答案:

答案 0 :(得分:2)

打开文件后,调用fgets() 3次以跳过这些行。

$open = fopen('employee-data.txt','r');
# skip heading lines.
fgets($open);
fgets($open);
fgets($open);

此外,您不应该使用while (!feof($open)),请参阅PHP - while loop (!feof()) isn't outputting/showing everything

使用:

while ($explodedLine = fgetcsv($open)) {
    ...
}

答案 1 :(得分:-1)

使用一个变量来计数行数,如果其值小于要跳过的行数,则跳过循环。

$row = 0;
while (!feof($open)) {
    $getTextLine = fgets($open);

    if ($row++ < 3)
        continue;

    // ...
}