Show only five first lines from text file

陌路散爱 提交于 2019-12-11 19:19:01

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!