Alex
Alex

Reputation: 4934

Reading lines from a file in PHP

I'm having problems reading lines from a text file in PHP.

I have this code:

$a_path = "./data/answers.txt";

    $answers = fopen($a_path);

    $line_num = 1;

    while ($line = fgets($answers))
    {
        for ($i = 0; $i < count($common_q_line_nums); $i++)
        {
            if ($line_num == (int)$common_q_line_nums[$i])
            {
                echo $line;
            }
        }
        $line_num++;
    }

I am using Macintosh, however I updated the php.ini file with auto_detect_line_endings = On

The $common_q_line_nums sorted array contains numbers in the range of the lines in the text file.

Any idea why I'm getting nothing back? The file is opening ok, and the $common_q_line_nums is good.

Appreciated, Alex

Upvotes: 0

Views: 210

Answers (2)

genesis
genesis

Reputation: 50966

This one is better

$lines = file("data/answers.txt"); // each line in one array index ($lines[0], $lines[1] etc)

Upvotes: 2

gen_Eric
gen_Eric

Reputation: 227200

There are few issues that I noticed here.

First is this line:

 $answers = fopen($a_path);

fopen is missing the mode parameter. It should be:

$answers = fopen($a_path, 'r');

Next, I'm not sure if this is a problem, but it may be. Change this:

while($line = fgets($answers))

to:

while(($line = fgets($answers)) !== FALSE)

Upvotes: 4

Related Questions