Forum Moderators: coopster

Message Too Old, No Replies

CSV File problem...

Reading from....

         

xeonaphobe

4:15 am on Jan 25, 2005 (gmt 0)

10+ Year Member



I've been working on a simple flat file blog using php and csv files. Everything seems to be working fine although I have come across one problem that I hope you can help me out with.

I have a csv file where each row contains an id number, the title of the article, and the article contents. I've displayed the latest 10 articles on my page with the following code;

$handle = fopen("crazyarticles.csv", "a+");
while (($data = fgetcsv($handle, 1000, " "))!== FALSE) {

echo "<TABLE bgcolor=\"black\" border=\"1\" width=\"550\"><TR><TD>" . $data[1] . "</td></tr>";
echo "<TR><TD>" . $data[2] . "</td></tr>";

$count++;

if ($count==10) {
echo "<a href=\"archives.php\">Previous Posts</a>";
exit();
}
}
fclose($handle);

This works fine, apart from one thing: it's displaying the articles in the order I wrote them rather than displaying the most recent (ie. it's reading from top to bottom from the CSV file).

Is there anyway I can get it to read from the bottom row up in the CSV so that my most recent article will be displayed at the top of the page? Any suggestions would be fantastic!

Cheers,
Neil

mincklerstraat

10:06 am on Jan 25, 2005 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



I'd try something like:

$handle = fopen("crazyarticles.csv", "a+");
$dataarray = array();
$count = 1;
while (($data = fgetcsv($handle, 1000, " "))!== FALSE) {
$dataarray[] = $data;
}
fclose($handle);
$dataarray = array_reverse($dataarray);
foreach($dataarray as $data){
echo "<TABLE bgcolor=\"black\" border=\"1\" width=\"550\"><TR><TD>" . $data[1] . "</td></tr>";
echo "<TR><TD>" . $data[2] . "</td></tr>";
$count++;
if ($count==10) {
echo "<a href=\"archives.php\">Previous Posts</a>";
exit();
}
}

Once this csv file gets pretty long, you'll either want to write your own function that parses exclusively those lines that you want, to save memory, or else switch to a database (even better).

xeonaphobe

1:05 pm on Jan 25, 2005 (gmt 0)

10+ Year Member



Thanks for the speedy response :) I'll give that a try tonight and let you know how I get on. You're not the first person to suggest that i move onto a database. It'll obviously need to happen eventually, i'm just trying to put it off for as long as possible as I've never touched MySQL before :S

mincklerstraat

1:17 pm on Jan 25, 2005 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Once you get to it, mysql will go easier than you thought. Good luck with the project.