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"

if(file_exists('file.json'))
{	
	$filename = 'file.json';
	$data = file_get_contents($filename); //data read from json file
	print_r($data);  
	$users = json_decode($data);  //decode a data 
	
	print_r($users); //array format data printing
	 $message = "<h3 class='text-success'>JSON file data</h3>";
}else{
	 $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>  
 <html>
<head>         
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:400,700">
  <title>Read a JSON File</title>  
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>

<style>
#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;
}
</style>
      </head>
	  <body>  
	   <div class="container" style="width:500px;">  
	   <div class="table-container">
	   <?php  
			 if(isset($message))  
			 {  
				  echo $message;  
			  
			 ?>
		<table id="tbstyle">
			<tbody>
				<tr>
					<th>Name</th>
					<th>Age</th>
					<th>Gender</th>
					<th>Education</th>
					<th>Occupation</th>
				</tr>
				<?php foreach ($users as $user) { ?>
				<tr>
					<td> <?= $user->name; ?> </td>
					<td> <?= $user->age; ?> </td>
					<td> <?= $user->gender; ?> </td>
					<td> <?= $user->education; ?> </td>
					<td> <?= $user->occupation; ?> </td>
				</tr>
				<?php } 
			 }
			 else
				echo $message; 
			 ?>
    </tbody>
</table>
</div>
</div>
</body>
</html>

Output