【问题标题】:How to delete two first lines in txt using PHP如何使用 PHP 删除 txt 中的前两行
【发布时间】:2018-11-13 19:34:26
【问题描述】:

例如我有数据:

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

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

$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之前删除行?

【问题讨论】:

  • 文件包含三个无用的行你如何检测到它?
  • 我的文件 txt 开头总是包含三个无用的行。我正在寻找跳过前三行、删除三行或从 4 行开始导入数据的解决方案。
  • 使用像$newStr = preg_replace("/^([^\n]+\n){3}/", "", $str)这样的正则表达式
  • 只测试 $explodeLine 的大小为 3 怎么样?如果没有记录并继续...

标签: php


【解决方案1】:

打开文件后,调用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)) {
    ...
}

【讨论】:

  • 未测试,但fgetcsv 可能会给你一个空数组作为空行,空数组是假的。
  • 我假设唯一的空行是开头的那一行。
【解决方案2】:

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

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

    if ($row++ < 3)
        continue;

    // ...
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-02-01
    • 2019-04-12
    • 1970-01-01
    • 2012-04-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-21
    相关资源
    最近更新 更多