PHP中每行TXT,增加变量值?

时间:2012-04-12 19:36:56

标签: php parsing loops time increment

我有以下代码读取TXT文件,从每行中提取不需要的信息,然后将编辑的行存储在新的TXT文件中。

<?php
$file_handle = fopen("old.txt", "rb");
ob_start();

while (!feof($file_handle) ) {

$line_of_text = fgets($file_handle);
$parts = explode('\n', $line_of_text);

foreach ($parts as $str) {
 $str_parts = explode('_', $str); // Split string by _ into an array
 array_pop($str_parts); // Remove last element
 array_shift($str_parts); // Remove first element
 echo implode('_', $str_parts)."\n"; // Put it back together    (and echo newline)
}
}

$new_content = ob_get_clean();
file_put_contents("new.txt", $new_content);

fclose($file_handle);
?>

我现在想插入$ hr #min和$ sec变量,每次保存新行时,这些变量将增加1秒。假设我的行读起来像这样(旧代码):

958588
978567
986766

我希望我的新代码看起来像这样:

125959958588
130000978567
130001986766

正如您所看到的,小时是24小时格式(00 - 23),接着是分钟(00 - 59),秒是(00 - 59),最后是提取的txt。

我已经制定了变量框架,但我不知道如何让vriables正确增加。有人可以帮忙吗?

<?php
$file_handle = fopen("old.txt", "rb");
$hr = 00;
$min = 00;
$sec = 00;
ob_start();

while (!feof($file_handle) ) {

$line_of_text = fgets($file_handle);
$parts = explode('\n', $line_of_text);

foreach ($parts as $str) {
 $str_parts = explode('_', $str); // Split string by _ into an array
 array_pop($str_parts); // Remove last element
 array_shift($str_parts); // Remove first element
 echo $hr.$min.$sec.implode('_', $str_parts)."\n"; // Put it back together  (and echo newline)
}
}

$new_content = ob_get_clean();
file_put_contents("new.txt", $new_content);

fclose($file_handle);
?>

3 个答案:

答案 0 :(得分:1)

我会更容易:

<?php
$contents = file('old.txt');
$time = strtotime('2012-01-01 00:00:00'); // Replace the time with the start time, the date doesn't matter
ob_start();

foreach ($contents as $line) {
    $str_parts = explode('_', $line); // Split string by _ into an array
    array_pop($str_parts); // Remove last element
    array_shift($str_parts); // Remove first element

    echo date('His', $time) . implode('_', $str_parts) . "\n"; // Put it back together  (and echo newline)

    $time += 1;
}

$new_content = ob_get_clean();
file_put_contents("new.txt", $new_content);

答案 1 :(得分:0)

我认为你在内循环中寻找类似的东西:

$sec++;
if (($sec==60) { 
    $min++; 
    $sec=0 
    if (($min==60) { 
        $hr++; 
        $min=0; 
        if (($hr==25) { $hr=0; }
    }
}

答案 2 :(得分:0)

您拥有的格式是UNIX域中的日期,例如第一个日期:

gmdate('His', 0);    # 000000
gmdate('His', 60);   # 000100
gmdate('His', 3600); # 010000

所以你可以传递秒数,gmdate函数会为你格式化。