dongtiandexue123456 2018-11-13 19:34
浏览 102
已采纳

如何使用PHP删除txt中的两个第一行

For example I have data:

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

and simple php code to import data into 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);

It works fine, but problem is on start read file, because file contains three useless lines (two with text and last one is empty). How can I delete lines before start import data into mysql?

  • 写回答

2条回答 默认 最新

  • dtx9763 2018-11-13 19:43
    关注

    After opening the file, call fgets() 3 times to skip over those lines.

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

    Also, you shouldn't use while (!feof($open)), see PHP - while loop (!feof()) isn't outputting/showing everything

    Use:

    while ($explodedLine = fgetcsv($open)) {
        ...
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!