tags:

views:

127

answers:

8

Hi there, I just figured out how to read some files but I really don't like it.

I have some files named 1.txt, 2.txt, 3.txt and so on. I need to read and print just the last 2 files. I found a way to do it but I would like to see some other ways to do it.

My way:

    <?php

$i = 1;
$x = 1;

while (file_exists('news/'.$i.'.txt')){
    $i++;
}

$i--;

while ((file_exists('news/'.$i.'.txt')) && ($x <= 2)){
    $data = file_get_contents('news/'.$i.'.txt'); 
    echo $data;
    $i--;
    $x++;
}

?>

Thanks!!

+3  A: 

it looks like a good way of doing it, what is wrong with it?

Quinn Wilson
I agree with @lunky.
Pawka
It's inefficient for one
amr
A: 

I would do it this way, I think it's more readable:

$allTextFiles = glob('news/*.txt');
$numericTextFiles = array_filter($allTextFiles, create_function('$file', 'return is_numeric(basename($file, ".txt"));'));
asort($numericTextFiles);
readfile(end($numericTextFiles));
readfile(prev($numericTextFiles));
soulmerge
+2  A: 

It would be convenient if you had database records of the news items, so that you could just query the database instead of reading from disk. However, if that's not an option, you might consider something like:

$files = scandir('news/', 1);
for($i = 0; $i < 2; $i++) {
    $data = file_get_contents($files[0]);
    echo $data;
}

This uses the scandir function in PHP 5.

VoteyDisciple
+3  A: 

Alternatively, you can load all of the file-names into an array with scandir(), and then read only the last two files mentioned in the array:

Jonathan Sampson
A: 

If they are the only files in the directory you can read all the files in the directory using readdir:

http://www.howtogeek.com/howto/programming/php-display-a-customizeable-list-of-files-in-a-directory/

kilrizzy
+1  A: 
$files = glob('news/*.txt'); // This is assuming all *.txt files have numbers for the * part

$files = rsort($files);

for ($x = 0; $x < 2; $x++) {
    readfile($files[$x]); 
}

Although, you could probably substitute scandir for the glob/rsort lines, as per Jonathan Sampson's answer.

You ARE using PHP5 by now, yes?

R. Bemrose
+1  A: 
<?PHP

$array = scandir($dir);    

$num = count($array);

$data1 = file_get_contents($array[$num-2]); //almost last file
$data2 = file_get_contents($array[$num-1]); //last file

echo $data1, $data2;

?>
+1  A: 

There might be a problem with the scandir() approach: The file names are sorted lexicographically, i.e. 1.txt, 10.txt, 11.txt, 2.txt, 20.txt, 3.txt,...
Therefore if you really want to change your code I'd suggest scandir()/glob() and natsort():

This function implements a sort algorithm that orders alphanumeric strings in the way a human being would while maintaining key/value associations.
$files = glob('news/*.txt');
natsort($files);
$files = array_slice($files, -2);
VolkerK