4

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>
2
  • 1
    That is not a table but a input field Commented Apr 25, 2011 at 15:06
  • This thread has been answered here Click here Commented Nov 2, 2017 at 6:12

3 Answers 3

9

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?

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

0

You can use this library for converting Json to Standard HTML table: Json-To-Html-Table

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.