我有以下代码读取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);
?>
我会更容易:
<?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);
我认为您正在内部循环中寻找类似的东西:
$sec++;
if (($sec==60) {
$min++;
$sec=0
if (($min==60) {
$hr++;
$min=0;
if (($hr==25) { $hr=0; }
}
}
您拥有的格式是 UNIX 域中的日期,例如第一个日期:
gmdate('His', 0); # 000000
gmdate('His', 60); # 000100
gmdate('His', 3600); # 010000
因此,您只需传入秒数,gmdate 函数将为您格式化它。