php只读第一行列表

时间:2014-04-29 12:24:17

标签: php

我是php的新手,我不确定我做错了什么。我试图列出txt文件中的所有记录。但是,我的代码只显示第一行。如何让代码显示文件中的所有记录?

$count = 0;
$soldOut = 0;
$eventFile = fopen("performances.txt", "r");
$event = fgets($eventFile);

while ( feof($eventFile));
{
    list ($dateEvent, $performer, $ticketprice, $status) = explode(":", $event);
    if($status == "Yes")
    {
        $status =  "Tickets are still available";
        $count = $status +1;
    }
    else
    {
        $status =  "***SOLD OUT***";
        $soldOut = $status +1;
    }

    print("<tr><td>$dateEvent </td>");
    print("<td>$performer </td>");
    print("<td>$ticketprice </td>");
    print("<td>$status</td></tr>");
    $event = fgets($eventFile);
}

3 个答案:

答案 0 :(得分:1)

注意docs,你会发现你的循环应该是:

while( !feof($eventFile)) {
    $event = fgets($eventFile); // THIS is where you get the current line
    // do stuff here
}

答案 1 :(得分:0)

你可以这样读取文件。您可以在此http://us1.php.net/function.file-get-contents

上找到更多信息
<?php
$data = file_get_contents("performances.txt",FILE_USE_INCLUDE_PATH); //read the file
$convert = explode(":", $data); //create array separate by new line

for ($i=0;$i<count($convert);$i++) 
{
    echo $convert[$i].', '; //write value by index
}
?>

答案 2 :(得分:0)

按照http://www.php.net/manual/en/function.fgets.php

的指示进行循环播放

基本上,保持循环直到fgets nolonger返回任何内容,然后检查指针是否与文件末尾匹配。 我还建议你看看http://www.php.net/manual/en/function.stream-get-line.php 这些评论为绩效提升提供了理由。

$count = $soldOut = 0;
$eventFile = fopen("performances.txt", "r");
if ($eventFile) {
    # Keep reading as long as fgets returns content
    while ( ($event = fgets($eventFile)) !== false ) {
        list ($dateEvent, $performer, $ticketprice, $status) = explode(":", $event);
        if($status == "Yes") {
            $status =  "Tickets are still available";
            ++$count; # increase count with one
        } else {
            $status =  "***SOLD OUT***";
            ++$soldOut; # increase soldout with one
        }

        echo '<tr>',
            '<td>',$dateEvent,'</td>',
            '<td>',$performer,'</td>',
            '<td>',$ticketprice,'</td>',
            '<td>',$status,'</td>',
        '</tr>';
    }
    # something went wrong
    if (!feof($eventFile)) {
        echo "Error: unexpected fgets() fail\n";
    }
    # remember to close them files
    fclose($eventFile);
} else {
    # failed to open
}