0

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.

1 Answer 1

2

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>";
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.