【问题标题】:Dynamically display a CSV file as an HTML table on a web page将 CSV 文件动态显示为网页上的 HTML 表格
【发布时间】:2010-10-05 20:24:22
【问题描述】:

我想在服务器端获取一个 CSV 文件并将其动态显示为 html 表。 例如,这个:

Name, Age, Sex
"Cantor, Georg", 163, M

应该变成这样:

<html><body><table>
<tr> <td>Name</td> <td>Age</td> <td>Sex</td> </tr>
<tr> <td>Cantor, Georg</td> <td>163</td> <td>M</td> </td>
</table></body></html>

欢迎使用任何语言的解决方案。

【问题讨论】:

    标签: php html csv


    【解决方案1】:

    previously linked solution 是一段可怕的代码;几乎每一行都包含一个错误。请改用fgetcsv

    <?php
    echo "<html><body><table>\n\n";
    $f = fopen("so-csv.csv", "r");
    while (($line = fgetcsv($f)) !== false) {
            echo "<tr>";
            foreach ($line as $cell) {
                    echo "<td>" . htmlspecialchars($cell) . "</td>";
            }
            echo "</tr>\n";
    }
    fclose($f);
    echo "\n</table></body></html>";
    

    【讨论】:

    • 太棒了!太感谢了。我想我会继续从问题中删除该链接。
    • 只想说,这是迄今为止我发现的最好的代码——干得好,先生!
    • 复制粘贴即可!谢谢! :)
    • @phihag。您能否提供一个使用您的代码的示例?提前致谢
    • @ddpd 您可以创建一个新的 php 文件,插入此代码并运行它。这已经是一个例子了;)
    【解决方案2】:

    下面是一个简单的函数,用php将csv转换为html表格:

    function jj_readcsv($filename, $header=false) {
    $handle = fopen($filename, "r");
    echo '<table>';
    //display header row if true
    if ($header) {
        $csvcontents = fgetcsv($handle);
        echo '<tr>';
        foreach ($csvcontents as $headercolumn) {
            echo "<th>$headercolumn</th>";
        }
        echo '</tr>';
    }
    // displaying contents
    while ($csvcontents = fgetcsv($handle)) {
        echo '<tr>';
        foreach ($csvcontents as $column) {
            echo "<td>$column</td>";
        }
        echo '</tr>';
    }
    echo '</table>';
    fclose($handle);
    }
    

    可以像jj_readcsv('image_links.csv',true);这样调用这个函数

    如果第二个参数为真,则 csv 的第一行将作为标题/标题。

    希望这对某人有所帮助。请评论此代码中的任何缺陷。

    【讨论】:

      【解决方案3】:

      phihag 的回答将每一行放在一个单元格中,而您要求将每个值放在一个单独的单元格中。这似乎做到了:

      <?php
      // Create a table from a csv file 
      echo "<html><body><table>\n\n";
      $f = fopen("so-csv.csv", "r");
      while (($line = fgetcsv($f)) !== false) {
              $row = $line[0];    // We need to get the actual row (it is the first element in a 1-element array)
              $cells = explode(";",$row);
              echo "<tr>";
              foreach ($cells as $cell) {
                  echo "<td>" . htmlspecialchars($cell) . "</td>";
              }
              echo "</tr>\n";
      }
      fclose($f);
      echo "\n</table></body></html>";
      ?>
      

      【讨论】:

        【解决方案4】:

        刚刚改进了phihag's 代码,因为如果文件不存在,它将进入无限循环。

        <?php
        
        $filename = "so-csv.csv";
        
        echo "<html><body><table>\n\n";
        
        if (file_exists($filename)) {
        $f = fopen($filename, "r");
        while (($line = fgetcsv($f)) !== false) {
                echo "<tr>";
                foreach ($line as $cell) {
                        echo "<td>" . htmlspecialchars($cell) . "</td>";
                }
                echo "</tr>\n";
        }
        fclose($f);
        }
        
        else{ echo "<tr><td>No file exists ! </td></tr>" ;}
        echo "\n</table></body></html>";
        ?>
        

        【讨论】:

          【解决方案5】:

          这是更新了一些引导程序的工作解决方案。 小表、条纹、边框和悬停突出显示

          function jj_readcsv($filename, $header = false)
          {
              $handle = fopen($filename, "r");
              echo '<div class="table-responsive"><table class="table table-sm table-striped table-bordered table-hover">';
              //display header row if true
              if ($header) {
                  $csvcontents = fgetcsv($handle);
                  echo '<tr>';
                  foreach ($csvcontents as $headercolumn) {
                      echo "<th>$headercolumn</th>";
                  }
                  echo '</tr>';
              }
              // displaying contents
              while ($csvcontents = fgetcsv($handle)) {
                  echo '<tr>';
                  foreach ($csvcontents as $column) {
                      echo "<td style='width:1px; white-space:nowrap;'>$column</td>";
                  }
                  echo '</tr>';
              }
              echo '</table></div>';
              fclose($handle);
          }
          

          【讨论】:

            【解决方案6】:

            如果你用 \ 转义引用的逗号,它会起作用吗?

            姓名、年龄、性别

            “康托尔\,乔治”,163,M

            大多数分隔格式都需要对其分隔符进行转义才能正确解析。


            一个粗略的 Java 示例:

            import java.util.Iterator;
            
            public class CsvTest {
            
                public static void main(String[] args) {
                    String[] lines = { "Name, Age, Sex", "\"Cantor, Georg\", 163, M" };
            
                    StringBuilder result = new StringBuilder();
            
                    for (String head : iterator(lines[0])) {
                        result.append(String.format("<tr>%s</tr>\n", head));
                    }
            
                    for (int i=1; i < lines.length; i++) {
                        for (String row : iterator(lines[i])) {
                            result.append(String.format("<td>%s</td>\n", row));
                        }
                    }
            
                    System.out.println(String.format("<table>\n%s</table>", result.toString()));
                }
            
                public static Iterable<String> iterator(final String line) {
                    return new Iterable<String>() {
                        public Iterator<String> iterator() {
                            return new Iterator<String>() {
                                private int position = 0;
            
                                public boolean hasNext() {
                                    return position < line.length();
                                }
            
                                public String next() {
                                    boolean inquote = false;
                                    StringBuilder buffer = new StringBuilder();
                                    for (; position < line.length(); position++) {
                                        char c = line.charAt(position);
                                        if (c == '"') {
                                            inquote = !inquote;
                                        }
                                        if (c == ',' && !inquote) {
                                            position++;
                                            break;
                                        } else {
                                            buffer.append(c);
                                        }
                                    }
                                    return buffer.toString().trim();
                                }
            
                                public void remove() {
                                    throw new UnsupportedOperationException();
                                }
                            };
                        }
                    };
                }
            }
            

            【讨论】:

            • 我认为示例解决方案无法解决这个问题。但我也不认为转义逗号是必要的,因为它们在引号中。 (另一方面,转义引号是可以的。)例如,mysql 导出到 CSV 时没有转义逗号。
            【解决方案7】:

            HTML ... 标签本身可以做到这一点,即没有 PHP 或 java。

            或查看这篇文章以了解上述内容的完整详细信息(包含所有选项..)。

            http://www.linuxquestions.org/questions/programming-9/how-to-show-csv-data-as-html-in-internet-explorer-with-filter-buttons-4175443612/

            【讨论】:

              【解决方案8】:

              定义“动态显示”?这意味着该表是通过 javascript 和某种 Ajax-y 更新构建的。如果您只想使用 PHP 构建表,那真的不是我所说的“动态”

              【讨论】:

              • PHP 在服务器端为每个 Web 请求生成它对我来说已经足够好了。如果您有 ajaxy 解决方案,最好将其包含在此处以供其他人稍后搜索。
              【解决方案9】:

              XmlGrid.net 具有将 csv 转换为 html 表的工具。链接在这里: http://xmlgrid.net/csvToHtml.html

              我使用了你的示例数据,得到了下面的 html 表格:

              <table>
              <!--Created with XmlGrid Free Online XML Editor (http://xmlgrid.net)-->
              <tr>
                <td>Name</td>
                <td> Age</td>
                <td> Sex</td>
              </tr>
              <tr>
                <td>Cantor, Georg</td>
                <td> 163</td>
                <td> M</td>
              </tr>
              </table>
              

              【讨论】:

              • 他说“动态”,你的解决方案不允许这样做
              猜你喜欢
              • 1970-01-01
              • 2014-02-01
              • 1970-01-01
              • 2011-03-30
              • 2016-12-21
              • 1970-01-01
              • 2019-08-21
              • 1970-01-01
              相关资源
              最近更新 更多