Forum Moderators: coopster
So what my question is..I've made a shoutbox, but the last post is coming at the end of the shout list... So what I've figured out is that I might have to read the file from the bottom and up. I've been reading around on php.net about everything related to file() and fread()/fwrite() etc... but I cant get it to work...
So my question is basicly how?
right now my read code looks like this
<?php
$fh = @fopen("shout/msg.txt", "r");
if ($fh) {
$i = 1;
while (!feof($fh)) {
$shout[$i] = fgets($fh, 4096);
$i++;
}
while ($i = 1) {
echo $shout[$i];
$i-1;
}
fclose($fh);
}
?>
and i know it's wrong since it dont work.. Been trying to edit examples from php.net to fit what I need it to do, but with no luck..
there's absolutely nothing there now except the shoutbox... since i started the site today... and I've decided to make everything myself =) so it's gonna take a lil time before i get it fully functional :)
[edited by: coopster at 9:55 pm (utc) on April 4, 2007]
[edit reason] no personal urls please TOS [webmasterworld.com] [/edit]
You could use file() [php.net] to read the text file into an array and then use array_reverse [php.net].
<?php
$filename = "filename.txt";
$fd = fopen($filename, "r");
$buffer = fread($fd, filesize($filename));
fclose($fd);
echo $buffer;
}
?>
and the instead of using the echo i add it to the array and the use the reverse function? *going to read about arrays* never worked with it before... this is going to be interesting =)
My code now is:
<?php
$fh = fopen("shout/msg.txt", "r");
if ($fh) {
while (!feof($fh)) {
$buffer = fgets($fh, 4096);
if ($buf_array == '') { $buf_array = $buffer; }
else { $buf_array = $buf_array . $buffer; }
}
fclose($fh);
$buffer = array($buf_array);
$shout = array_reverse($buffer);
print_r($shout);
}
?>
-------------
And it prints out:
Array ( [0] =>
Ole: Testing 1
Ole: Testin 2
)
So something is still not working...
// this will read file into array, each line into separate array item
$text = file('filename.txt');
// loop through array and output contents
for($i = sizeof($text); $i > 0; $i--) {
echo $text[$i-1] . "<br />";
}
OR this
// this will read file into array, each line into separate array item
$text = file('filename.txt');
// reverse array
$text= array_reverse($text);
// loop through array and output contents
foreach($text as $line) {
echo $line . "<br />";
}
First one is a little faster since it will not have to reverse array, while second is easier to understand