dongqi7631
dongqi7631
2014-07-03 19:27

将文件读入表时未定义的偏移错误

已采纳

I've got Undefined Offset error, but I don't know what's wrong.

Here's the code

<?php

        $documentRoot = $_SERVER['DOCUMENT_ROOT'];
        $fileName = "$documentRoot/Tutorials/PHP/Assignments/Assignment 3/data/quote.txt";
        $filePointer = fopen($fileName, 'r');

        $lineCounter = 0;
        $display = "";

        while(true)
        {

            $line = fgets($filePointer);
            list($firstName, $lastName, $contactMethod, $phoneMail, $resideCity, $comments) = explode("|", $line);

            if (!isset($comments))
            {
                $comments = "";
            }

            $lineCounter++;

            if(feof($filePointer))
            {
                break;
            }

            if($lineCounter % 2 == 0)
            {
                $style = "style = 'background-color:white';";
            }
            else
            {
                $style = "style = 'background-color:lightgray';";
            }

            //Write to table

            print"<tr $style>";
            print"<td>$firstName</td>";
            print"<td>$lastName</td>";
            print"<td>$contactMethod</td>";
            print"<td>$phoneMail</td>";
            print"<td>$resideCity</td>";
            print"<td>$comments</td>";
            print"</tr>";
        }

            fclose($filePointer);




        ?>

I added:

            if (!isset($comments))
            {
                $comments = "";
            }

Because I assume the offset error appears because I didn't type in anything in comments. However, I still get this error.

Please help.

Here's the error message:

Notice: Undefined offset: 5 in /Users/Lio/Documents/Eligio's/Tutorials/PHP/Assignments/Assignment 3/quotes.php on line 32

Notice: Undefined offset: 4 in /Users/Lio/Documents/Eligio's/Tutorials/PHP/Assignments/Assignment 3/quotes.php on line 32

Notice: Undefined offset: 3 in /Users/Lio/Documents/Eligio's/Tutorials/PHP/Assignments/Assignment 3/quotes.php on line 32

Notice: Undefined offset: 2 in /Users/Lio/Documents/Eligio's/Tutorials/PHP/Assignments/Assignment 3/quotes.php on line 32

Notice: Undefined offset: 1 in /Users/Lio/Documents/Eligio's/Tutorials/PHP/Assignments/Assignment 3/quotes.php on line 32

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

1条回答

  • douwen1313 douwen1313 7年前

    The problem is before your isset... so when you do explode and pass results to list... that expects 6 parametes only receive 5 or less and you get the error.

    I suggest the following replacement:

    $line = fgets($filePointer);
    $data=explode("|", $line);
    while(count($data)<6) $data[]="";
    list($firstName, $lastName, $contactMethod, $phoneMail, 
    $resideCity, $comments) = $data;
    

    That will add enough data for list to set vars.

    and should work!

    Happy coding!

    点赞 评论 复制链接分享