-2

I need to make a blog using a TXT file for a school project. In the text file $blog [0] is the title of the message, $blog1 is the username and $blog[2] is the message itself.

    $file = fopen('blogs.txt', 'r');

    while(!feof($file)) {
        $blog = fgets($file);
        $blog = explode("*", $blog);

        echo "
        <p><strong>". $blog[0]. "</strong>
        <br>By: ". $blog[1]. 
        "<br>". $blog[2];
    }

The page shows all the messages. But at the bottom I have a couple of 'Undefined Offsets: 1' and 'Undefined offset: 2's. It also says 'By: ' (as shown in the echo) a couple of times.

This is what the page looks like

  • 3
    These are most likely empty lines you read in for which the `explode()` command fails to produce more than a single empty element. I suggest you add the file content to your question. – arkascha Sep 27 '16 at 08:17
  • You had a array of one element, so you can access $blob[0] ,but can't $blob[1], bz it not exists – Janaka Sep 27 '16 at 08:19

1 Answers1

1

Check if explode returns more than one element:

$blog = explode("*", $blog);

id (count($blog) >= 3) { 
    echo "
    <p><strong>". $blog[0]. "</strong>
    <br>By: ". $blog[1]. 
    "<br>". $blog[2];
} else {
    //do some other stuff 
}
rbr94
  • 2,227
  • 3
  • 23
  • 39
  • It only shows one message but no error codes, which is a good start. How do I make it show more than one? – Wouter de Lange Sep 27 '16 at 08:23
  • Correct your data from what you read. Otherwise use the `else` part to catch this error and output alternative content – rbr94 Sep 27 '16 at 08:25