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 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器