Jump to content

[SOLVED] Need help reading news.txt backwards or appending to the top of the file.


Getintothegame

Recommended Posts

Hello!

 

I have a very basic news script for the main page of my website. It's simply a text file that I append lines to in a separate file called newspost.php. However, whenever a new post is added, it adds itself to the bottom of the file, so it's old news first. I need a script that will read or append backwards.

 

I think it needs to be split into an array, but I'm at a loss on how to do this with this situation. Here's my current news reading script:

 

<?php
$news = file("news.txt");
foreach($news as $mynews) {
$n_title = strtok($mynews,"¶");
$n_text = strtok("¶");
echo "<span class=star>$n_title</span><br>
$n_text<br><br>";
} 
?>

 

Thank you very much!

Oh, and some sample data in the news.txt file would be:

 

2/19/2007: Guess What?!¶I got bored, ...

2/15/2007: Server Downtime¶Okay, I promised more stability...

2/13/2007: Updated Server!¶Sorry for the downtime...

I recommend that you use a mysql database instead of using a text file to store your news.  I think there is also a way to append to the beginning of a file, instead of the bottom, I'll look into it right now, will edit.

Or this, it might be slow though, it gets the data already in there by opening the file as read only, then opens the same file with read and write access and writes your new content, then adds the old content to it:

 

<?php
$path = "./test.txt";
$handle = fopen($path, 'r');
$oldcontent = fread($handle, filesize($path));
$handle = fopen($path, 'w+');
$content = "[NEW NEWS ITEM]" . $oldcontent;
//echo $content;
if(!fwrite($handle, $content)) {
  echo "File write failed.";
  } else {
  echo "Success!";
  }
fclose($handle);
?>

 

Change $path, and [NEW NEWS ITEM] and it should work for you.

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.