How To Read JSON File And Display In A Table Using PHP

This article will discuss how to read a JSON file and display the details in table format using PHP. To use PHP function file_get_contents () we can read a file and retrieve the data present in JSON file. After retrieving data need to convert the JSON format into an array format. Then with the use of looping statement will display as a table format.

JSON input file - file.json

	{ "name":"xxxx","age":"23","gender":"female","education":"BTech","occupation":"developer"},
	{ "name":"YYYY","age":"30","gender":"male","education":"BE","occupation":"programmer"},
	{ "name":"zzz","age":"20","gender":"female","education":"MBA","occupation":"HR"},
	{ "name":"XYZ","age":"40","gender":"male","education":"CA","occupation":"auditor"}   

The below code will confirm if a JSON file is present or not. If a JSON file is not there it will display  "JSON file Not found"

	$filename = 'file.json';
	$data = file_get_contents($filename); //data read from json file
	$users = json_decode($data);  //decode a data 
	print_r($users); //array format data printing
	 $message = "<h3 class='text-success'>JSON file data</h3>";
	 $message = "<h3 class='text-danger'>JSON file Not found</h3>";

Once we get array details using foreach loop we will display output in the table

<!DOCTYPE html>  
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link rel="stylesheet" href=",700">
  <title>Read a JSON File</title>  
<link rel="stylesheet" href="">
<script src=""></script>

#tbstyle {
  font-family: Arial, Helvetica, sans-serif;
  border-collapse: collapse;
  width: 50%;

#tbstyle td, #tbstyle th {
  border: 1px solid #ddd;
  padding: 8px;

#tbstyle tr:nth-child(even){background-color: #f2f2f2;}

#tbstyle tr:hover {background-color: #ddd;}

#tbstyle th {
  padding-top: 12px;
  padding-bottom: 12px;
  text-align: left;
  background-color: #859161;
  color: White;
	   <div class="container" style="width:500px;">  
	   <div class="table-container">
				  echo $message;  
		<table id="tbstyle">
				<?php foreach ($users as $user) { ?>
					<td> <?= $user->name; ?> </td>
					<td> <?= $user->age; ?> </td>
					<td> <?= $user->gender; ?> </td>
					<td> <?= $user->education; ?> </td>
					<td> <?= $user->occupation; ?> </td>
				<?php } 
				echo $message; 


Similar Articles