Jump to content

Print specific number of lines from a file.


yoob

Recommended Posts

There are many ways to do that, the best way depends on the size of the file, I think.

Small file:
[code]<?php
$output = array_slice(file($filepath), 0, 10);
?>[/code]
Do whatever you want with the new array..

Larger file:
[code]<?php
$handle = fopen("filename","r");

for($i=0;$line = fgets ($handle,4096) && $i<10;$i++){
  echo  $line;
}
?>[/code]

Making fgets part of the condition prevents you get errors when the file is shoter than 10 lines.
Link to comment
Share on other sites

Hmm, another problem.

See, i have this small piece of line reverse code, making the bottom lines of the file show up at the top. I've put it together myself so it may not be perfect:

[code]<?

        $file=fopen("news/news.txt", "r");
        flock($file,1);

        $plik= array();
        while (!feof($file)){
                $plik[] = fgets($file,5000);
        }

        flock($file,3);
        fclose($file);

        for ($i=count($plik); $i>= 0; $i--){
        echo $plik[$i];
        }
?>[/code]

I try to merge it with the code you guys provided, but i dont think im skilled enough to understand all this. Could you help me out?
Link to comment
Share on other sites

You're doing this:

for ($i=count($plik); $i>= 0; $i--){
        echo $plik[$i];

Saying:

start a loop
assign $i the value of the highest index in the array I want to fetch from
echo the value of my array that has index $i

keep looping, while $i is greater or equal than 0 doing the following:
for each loop, decrease $i by one
for each loop echo the value of my array that has index $i


resulting in, for say an array with 20 values:

$arr[20]
$arr[19]
$arr[18]
etc...

Get it?

You have to fetch the values in the same order you put them in there!
Link to comment
Share on other sites

Alright. I studied the php.net manuals, and everything you said, and i came up with this little thing:

[code]        $number = count($plik)-10;

        for ($i=count($plik); $i>=$number ; $i--){
        echo $plik[$i];
        }
[/code]

And it works ^______^

Thanks a lot.
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.