如何在每行[PHP]的开头追加数字?
我有test.txt和以下数据如何在每行[PHP]的开头追加数字?,php,append,Php,Append,我有test.txt和以下数据 2015-06-19 14:46:10 10 2015-06-19 14:46:11 20 2015-06-19 14:46:12 30 (自动生成,无法编辑) 然后,我使用以下php脚本写入名为tempdata.txt的临时文件 <?php $myFile = "filelocation/test.txt"; $myTempFile = "filelocation/tempdata.txt"; $string = file_
2015-06-19 14:46:10 10
2015-06-19 14:46:11 20
2015-06-19 14:46:12 30
(自动生成,无法编辑)
然后,我使用以下php脚本写入名为tempdata.txt的临时文件
<?php
$myFile = "filelocation/test.txt";
$myTempFile = "filelocation/tempdata.txt";
$string = file_get_contents($myFile, "r");
$string = preg_replace('/\t+/', '|', $string);
$fh = fopen($myTempFile, 'w') or die("Could not open: " . mysql_error());
fwrite($fh, $string);
fclose($fh);
?>
但是,我想在每行的开头添加行号,如下所示:
1|2015-06-19 14:46:10|10
2|2015-06-19 14:46:11|20
3|2015-06-19 14:46:12|30
是否有任何方法可以用php读取行号并将其添加到每行的前面,如“n |”?以实现这一点,您需要逐行读取文件。 你可以在一段时间内这样做
$count = 0;
$myFile = "filelocation/test.txt";
$myTempFile = "filelocation/tempdata.txt";
$string = fopen($myFile, "r");
$fh = fopen($myTempFile, 'w') or die("Could not open: " . mysql_error());
while ($line = fgets($string)) {
// +1 on the count var
$count++;
$line = preg_replace('/\t+/', '|', $line);
// the PHP_EOL creates a line break after each line
$line = $count . '|' . $line . PHP_EOL;
fwrite($fh, $line);
}
fclose($fh);
这样的事情应该能够实现你想要的。我没有测试它,所以你可能需要更改一些东西。第15行:意外的“{”at:while($Line=fgets($string)){这很奇怪,尽管你打开了while循环。@MieerDarwesh我更改了我的代码((而不是(在开始时>)。哈哈:p这个问题已经解决了,但是它说:fgets()期望参数1是资源,字符串在..中给出,第16行是:while($line=fgets($string))@MieerDarwesh Ah是的,您应该使用fopen我再次更改代码Hanks dude(dankjewel)
$count = 0;
$myFile = "filelocation/test.txt";
$myTempFile = "filelocation/tempdata.txt";
$string = fopen($myFile, "r");
$fh = fopen($myTempFile, 'w') or die("Could not open: " . mysql_error());
while ($line = fgets($string)) {
// +1 on the count var
$count++;
$line = preg_replace('/\t+/', '|', $line);
// the PHP_EOL creates a line break after each line
$line = $count . '|' . $line . PHP_EOL;
fwrite($fh, $line);
}
fclose($fh);