LucN LucN - 1 year ago 102
PHP Question

Display json in html

Hi guys, I would like to display data from a MySQL table in a HTML file. I have a working PHP file:

$mysqli = new mysqli("localhost","user","pass","db");
if (mysqli_connect_errno()) {
printf("Can't connect to SQL Server. Error Code %s\n", mysqli_connect_error($mysqli));
$name = $_POST['name'];
// Set the default namespace to utf8
$mysqli->query("SET NAMES 'utf8'");
$json = array();
if($result = $mysqli->query("SELECT name, device, punkte FROM freefallhighscores ORDER BY punkte DESC LIMIT 0, 50")) {
while ($row=$result->fetch_assoc()) {

header("Content-Type: text/json");
echo json_encode(array( 'results' => $json ));


When I run the PHP file, I get the expected echo:

{"results":[{"name":"Benane","device":"iPhone4,1","punkte":"5000"},{"name":"Tillazh","device... and so on.

Now I want to display this data in an HTML table. To do so, I have to pass the data (JSON variable) to an HTML file (maybe using the $_POST function?). How can I do this? Would it be appropriate to use an XMLHttpRequest (XHR)?

Answer Source

Yes, unless you are going to use this pattern a lot of times, and even then, since you're already exporting the database table from PHP and are not using multiple target formats, there is no need to use JSON.

The simplest solution would be something like:

foreach ($json as $k=>$v){
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download