将JSON值转换为HTML表格

4
我有一个文件夹里包含 table.htmldata.phpjson.csv 三个文件。 data.php 文件使用 fopen("json.csv","r") 语句来读取 json.csv 文件。
如何在 table.html 中将 JSON 对象显示为表格?
<html>
<head>
<script type="text/javascript" src="jquery.js">
function display(){
 $.post('data.php',function(data){
 $("#txtJSON").html(data); 
 });
  }

  </script>
  </head>
  <body onload="display()">
  <table id="#jobtable">
  <input type="text" id="txtJSON" />
  </table>
  </body>
  </html>

1
那不是一个表格,而是一个输入字段。 - Prix
此线程已在此处得到解答 点击这里 - Delickate
3个回答

9
您只需要使用json_decode和一些迭代即可。 http://php.net/manual/en/function.json-decode.php 我将向您展示一种非常简单的PHP方法。 您没有提供有关JSON的任何信息,因此我假设它是平面的(而不是嵌套的)。 我认为您可能还想改变客户端的内容。 将txtJSON更改为空的div,该
将填充来自PHP的输出。
$file = $fopen("json.csv", 'r');
$fileText = fread($file, filesize($file));
$arr = json_decode($fileText, true); //i prefer associative array in this context

echo "<table>";
foreach($arr as $k=>$v)
    echo "<tr><td>$k</td><td>$v</td></tr>";
echo "</table>";

如果你的JSON数据不是扁平化和简单的,你希望结果表格看起来像什么?


2

Here I have taken json data in to $json variable, and then use foreach loop to create table from json data.

foreach ($data as $key => $jsons) {
 $table ='<table class="'.$jsons['class'].'" border="1">';
 foreach ($jsons as $rkey => $rvalue) {
    if($rkey=='head')
    {
        $table.='<tr>';
        foreach($rvalue as $rvv)
        {
            $table.='<th>'.$rvv.'</th>';
        }
        $table.='</tr>';
    }else
    if($rkey=='rows')
    {
        foreach($rvalue as $rvv)
        {
            $table.='<tr>';
            foreach($rvv as $rv)
            {
                $table.='<td>'.$rv.'</td>';
            }
            $table.='</tr>';
        }
    }
 }
}
echo $table;
?>

I have taken reference from http://www.tutsway.com/create-table-from-json.php


0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接