繁体   English   中英

使用PHP将CSV输出为HTML

[英]Output CSV to HTML using PHP

我有一个非常基本的问题,似乎很简单,但是我对这个概念感到困惑。

我正在尝试使用php将csv输出到html,这是我要输出为的代码。

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

这是我的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>";

?>

任何帮助将不胜感激,因为我似乎无法在相应的段落标签中正确输出第二行和第三行。

分析:

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

因此,请按原样解决这些问题(以及更好的缩进)

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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