drmticpet66231422 2015-10-26 07:30
浏览 55
已采纳

从php中的csv文件返回第n行

I have a csv file and have created the code to read the whole file into a table thus:

$table = "<table id='availabilitytableData'>

";

$f = fopen("assets/temp/test.csv", "r");

while (($line = fgetcsv($f)) !== false) {

$table .= "<tr>";

foreach ($line as $cell) {
$table .= "<td style='font-size:9pt;'>" . htmlspecialchars($cell) . "</td>";
}

$table .= "</tr>
";
}

fclose($f);
$table .= "
</table>";
return $table;

What is the best approach to select say just the 4th row from the csv file? I have tried various approaches along the lines of

$line = file($f);//file in to an array
return $line[4];

which gives me the line I want but not in a formatted table. Other code snippets e.g. like this give clues but I can't seem to adapt them to my purpose. Bit stuck here I'm afraid any pointers are most welcome

  • 写回答

1条回答 默认 最新

  • douxing6434 2015-10-26 08:04
    关注

    What about something nice and simple like this:

    $lineNo = 1;  //initialise a pointer
    
    while (...) {
    
        if($lineNo == 4){
    
            //output line 4
    
            break;  //to prevent any more looping after line 4
        }
    
        $lineNo++;  //increment the pointer
    }
    

    Option 2

    Or.. ..just extract line 4 from $line and dont bother with a loop.

    $line = fgetcsv($f));
    
    $line4 = $line[3];  //arrays are zero-indexed
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?