Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSON values into HTML table

Tags:

json

html

php

I have a table.html, data.php and json.csv within the same folder.

data.php is doing fopen("json.csv","r") to read from json.csv.

How can I display the JSON objects as a table within 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>
like image 518
user544079 Avatar asked Dec 21 '22 15:12

user544079


1 Answers

You just need json_decode and some iteration

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.

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

like image 100
jon_darkstar Avatar answered Dec 24 '22 04:12

jon_darkstar