0

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 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

Community
  • 1
  • 1
Grogorio
  • 5
  • 2

1 Answers1

1

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
MaggsWeb
  • 3,018
  • 1
  • 13
  • 23
  • Shouldn't `continue` be `break` instead? – Tanuel Mategi Oct 26 '15 at 08:06
  • @TanuelMategi Oh yeah.. ..Thanks! – MaggsWeb Oct 26 '15 at 08:06
  • Thanks for that idea Maggs, option 1 will do it for me, and I can easily add lines with ORs inside the IF statement. Option 2 looks like it has the potential to be a bit more compact, I will have a fiddle with that as well. Once again thank you for your input, I was having a brain freeze and you thawed me out. – Grogorio Oct 26 '15 at 08:45