php 在网页上动态显示 CSV 文件作为 HTML 表格

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/518795/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 22:57:35  来源:igfitidea点击:

Dynamically display a CSV file as an HTML table on a web page

phphtmlcsv

提问by dreeves

I'd like to take a CSV file living server-side and display it dynamically as an html table. E.g., this:

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

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

should become this:

应该变成这样:

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

Solutions in any language are welcome.

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

回答by phihag

The previously linked solutionis a horrible piece of code; nearly every line contains a bug. Use fgetcsvinstead:

所述先前连接的溶液是一种可怕的一段代码; 几乎每一行都包含一个错误。使用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>";

回答by Joby Joseph

Here is a simple function to convert csv to html table using php:

这是一个使用 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);
}

One can call this function like jj_readcsv('image_links.csv',true);

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

if second parameter is true then the first row of csv will be taken as header/title.

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

Hope this helps somebody. Please comment for any flaws in this code.

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

回答by user3257572

phihag's answer puts each row in a single cell, while you are asking for each value to be in a separate cell. This seems to do it:

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

回答by AKS

HTML ... tag can do that itself i.e. no PHP or java.

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

or see this post for complete detail on the above (with all options..).

或查看此帖子以获取有关上述内容的完整详细信息(包含所有选项......)。

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

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

回答by Kevin

Does it work if you escape the quoted commas with \ ?

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

Name, Age, Sex

"Cantor\, Georg", 163,M

姓名、年龄、性别

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

Most delimited formats require that their delimiter be escaped in order to properly parse.

大多数分隔格式都要求对它们的分隔符进行转义,以便正确解析。



A rough Java example:

一个粗略的 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();
                    }
                };
            }
        };
    }
}

回答by Scott Evernden

define "display it dynamically" ? that implies the table is being built via javascript and some sort of Ajax-y update .. if you just want to build the table using PHP that's really not what I would call 'dynamic'

定义“动态显示”?这意味着该表是通过 javascript 和某种 Ajax-y 更新构建的。

回答by Zac Zeng

XmlGrid.net has tool to convert csv to html table. Here is the link: http://xmlgrid.net/csvToHtml.html

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

I used your sample data, and got the following html table:

我使用了您的示例数据,并得到了以下 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>