简体   繁体   中英

return nth row from a csv file in php

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

$table = "<table id='availabilitytableData'>\n\n";

$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>\n";
}

fclose($f);
$table .= "\n</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 eg 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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM