Harry Berry
Harry Berry

Reputation: 65

Output CSV to HTML using PHP

I have a very basic question it seems very simple but I am getting stuck on the concept.

I am trying to output a csv to html using php and this is the code I want to output as.

<div class="row">
  <div class="col-1">
    <div class="in">
      <p class="description">FIRST CELL OF ROW HERE</p>
      <p class="town">SECOND CELL OF ROW HERE</p>
      <p class="city">THIRD CELL OF ROW HERE</p>
    </div>
  </div>
</div>

and here is my PHP

<?php

echo "<html><body><table>\n\n";
$f = fopen("test.csv", "r");
while (($line = fgetcsv($f)) !== false) {
    echo "<div class='row'";
    foreach ($line as $cell) {
        echo "<div class='col-1'><div class='in'>";
        echo "<p class='description'>" . htmlspecialchars($cell) . "</p>";
        echo "<p class='address'>" . htmlspecialchars($cell[1]) . "</p>";
        echo "<p class='town'>" . htmlspecialchars($cell[2]) . "</p>";
        echo "</div></div>";
    }
    echo "</div>";
}
fclose($f);
echo "\n</table></body></html>";

?>

Any help would be greatly appreciated as I can't seem to get the second and third row outputting correctly in there corresponding paragraph tags.

Upvotes: 0

Views: 101

Answers (1)

bernie
bernie

Reputation: 10400

Analysis:

while (($line = fgetcsv($f)) !== false) {
        echo "<div class='row'";
        // remove this foreach. You're iterating over the cells
        // when doing this. That is why $cell works while $cell[1]
        // does not ($cell is not an array at this point)
        foreach ($line as $cell) {   // <-- remove this foreach

        echo "<div class='col-1'><div class='in'>";    
// You are using $cell as a scalar and then as an array. It is one
// or the other, not both.
echo "<p class='description'>" . htmlspecialchars($cell) . "</p>";
echo "<p class='address'>" . htmlspecialchars($cell[1]) . "</p>";
echo "<p class='town'>" . htmlspecialchars($cell[2]) . "</p>";
echo "</div></div>";    
        }
        echo "</div>";
}
fclose($f);
echo "\n</table></body></html>";

So fixing those problems in your code as-is (and better indenting)

while (($line = fgetcsv($f)) !== false) {
    echo "<div class='row'";
    echo "<div class='col-1'><div class='in'>";
    echo "<p class='description'>" . htmlspecialchars($line[0]) . "</p>";
    echo "<p class='address'>" . htmlspecialchars($line[1]) . "</p>";
    echo "<p class='town'>" . htmlspecialchars($line[2]) . "</p>";
    echo "</div></div>";    
    echo "</div>";
}
fclose($f);
echo "\n</table></body></html>";

Upvotes: 2

Related Questions