问题
I have this code (from SteAp):
<?php
$file = fopen("news/news_2013.txt", "r");
$i = 0;
while (!feof($file)) {
$posts[] = fgets($file);
}
fclose($file);
foreach ($posts as $rawPost ){
$datePart = substr( $rawPost, 0, 19 );
$newsPart = substr( $rawPost, 20, 10000 );
echo $datePart . ': ' . $newsPart . '<br />';
}
?>
I use it here: http://flamencopeko.net/news. Works perfect.
I'm trying to make a version for the main page that shows only the five newst lines. Like this: http://flamencopeko.net/index2.php But only with the top five posts. So while (!feof($file)) will not work for this purpose.
Suggestions?
回答1:
Just use a counter and break out of the loop
$i = 0;
while (!feof($file)) {
$posts[] = fgets($file);
$i++;
if ($i >= 5) break;
}
来源:https://stackoverflow.com/questions/18454905/show-only-five-first-lines-from-text-file