php JSON 值转换为 HTML 表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5779729/
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
JSON values into HTML table
提问by user544079
I have a table.html, data.phpand json.csvwithin the same folder.
我在同一个文件夹中有一个table.html、data.php和json.csv。
data.phpis doing fopen("json.csv","r")
to read from json.csv.
data.php正在fopen("json.csv","r")
从json.csv读取。
How can I display the JSON objects as a table within table.html?
如何将 JSON 对象显示为table.html 中的表格?
<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>
回答by jon_darkstar
You just need json_decode
and some iteration
你只需要json_decode
一些迭代
http://php.net/manual/en/function.json-decode.php
http://php.net/manual/en/function.json-decode.php
I'll show you a very simplistic way to do the PHP. You don't tell anything about the JSON, so I'm assuming its flat (not nested). I think you might want to alter the client side stuff too. Make txtJSON
into an empty div
, which will be filled with the output from the 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>";
If your JSON is not flat and simple, what would you like the resulting table to look like?
如果您的 JSON 不是扁平和简单的,您希望结果表是什么样的?
回答by Manish
Here I have taken json data in to $json variable, and then use foreach loop to create table from json data.
这里我将 json 数据放入 $json 变量中,然后使用 foreach 循环从 json 数据创建表。
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
回答by Afshin Mehrabani
You can use this library for converting Json to Standard HTML table: Json-To-Html-Table
您可以使用此库将 Json 转换为标准 HTML 表:Json-To-Html-Table