MSD
MSD

Reputation: 313

How to append number at the beginning of each line [PHP]?

I have test.txt with the following data

2015-06-19 14:46:10 10 
2015-06-19 14:46:11 20 
2015-06-19 14:46:12 30

(this gets auto generated and can not be edited) I then use the following php script to write to a temp file called 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);
?>

which makes tempdata.txt look like:

2015-06-19 14:46:10|10
2015-06-19 14:46:11|20
2015-06-19 14:46:12|30

However I would like to add the line number at the start of each line like so:

1|2015-06-19 14:46:10|10
2|2015-06-19 14:46:11|20
3|2015-06-19 14:46:12|30

is there any way i can read the linenumber in php and add that to the front of each line like "n|" ?

Upvotes: 1

Views: 1525

Answers (1)

Szenis
Szenis

Reputation: 4170

To accomplish that you will need to read the file line by line. You could do that in a while loop like so

$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);

Something like that should be able to accomplish what you want.
I didnt test it so you might need to change a couple of things.

Upvotes: 1

Related Questions