Jump to content

Content of a file not displaying correctly.


membot

Recommended Posts

Hi! I'm a total stupid newbie. Please humor me.

So, I'm trying to make a guestbook, just as practice. So far I have a form that writes entries to a file, each entry on a new line. Entries look like this:

 

11:11 am, Oct 12th, 2010|name|website|message

 

My dividing character between parts of the entries is the vertical bar. I don't know if that's a bad idea. As I said, I'm a newb. I should probably find out how to make a code that makes it so people can't use that character in the form.

Anyway, this is my code so far trying to display the entries. So far, I just want to show the date of the first entry.

 

$file = fopen("posts.txt", 'rb');

while(!feof($file) && fgetc($file) != "|"){
$date = $date.fgetc($file);
}

echo $date;

fclose($file);

 

I already have a problem. The code does stop at the vertical bar, but instead of showing the date as "11:11 am, Oct 12th, 2010" it shows "11 m c 2h 00". I'm just super confused, and I don't know what to do.

Thanks. (:

You're getting a character in the while condition and then later inside the while.  Each time you do it moves to the next character.  You could probably do this:

 

$date = '';
while(!feof($file) && ($char = fgetc($file)) != "|"){
   $date .= $char
}

 

However I prefer single read functions, especially if you will be using more of the file.  Here's a simple way assuming that there are always exactly 3 pipes and it's always formatted the same way:

 

$lines = file('posts.txt');

foreach($lines as $line) {
   list($date, $name, $site, $msg) = explode('|', $line);
   //echo stuff
}

@Shawn - Oh! That totally makes sense, thanks! Now I see it was only showing every other character or so, haha. At first, I just thought it was nonsense. I tried something like the first code you put and it worked perfectly. And I'm sure that second code would be easier, it's just I don't know what some of those functions are yet. I'm learning from a book, so I want to go in the order the book does, and learn those when I get to them.

 

@Ken - Yeah, I know about that one, but I don't really know how arrays work yet. As I said above, I want to go in the order of the book, even if it is a bit silly.

 

Thanks, everyone. (:

You'll probably be seeing me around here later. I get stuck a lot.

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.