문제

$fileName = file ("gstbook.txt");
$rows = count ($fileName);

// $Char is the string that will be added to the file.
if ($Char != '') 
{
  $Char = str_replace ("\n","<br>",$Char);
  $Char = strip_tags ($Char, '<br>');

  $newRow = '<tr><td>' . ($username) . ": " . ($Char) . '</td></tr>';

  $oldRows = join ('', file ('gstbook.txt') );
  $fileName = fopen ('gstbook.txt', 'w');
  fputs ($fileName, $oldRows . chr(13) . chr(10) . $newRow);
  fclose ($fileName);
}

i'm working from a tutorial on a website. it's a guestbook program that i'm trying to turn into a tiny chat for use with one of my other apps.

where i'm stuck has to do with these two lines:

  $oldRows = join ('', file ('gstbook.txt') );

and:

  fputs ($fileName, $oldRows . chr(13) . chr(10) . $newRow);

I can tell it's inputting the entire file into a single string. then outputting that string. what i haven't been able to figure out from Google is how to make it input only the first n lines of a file into the $oldRows variable.

the good news is that the

</tr> 

of each file line can act as a delimiter. The bad news is i don't know where to go from there.

Would anyone tell me how to limit the input of the $oldRows variable to just n lines from $filename OR on how to trim down the $oldRows variable to just n lines?

CORRECTION:

i need to get the LAST n lines of the file (newest is added to the end)

도움이 되었습니까?

해결책

Try

array_map( 'trim', file( $filename ) );

this will return array of string, then you can use for/foreach

다른 팁

I would use array_slice

Here's an example:

$data = file('file.txt');
$data = array_slice($data, count($data) - 1, null, true);
print_r($data);

In the above code the count($data) - 1) is where you set the n parameter, in this case it is fetching the last line of the file.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top