如何使用 PHP 读取 JSON 文件并在表格中显示

作者 : 慕源网 本文共2120个字,预计阅读时间需要6分钟 发布时间: 2022-02-25 共875人阅读

本文将讨论如何使用 PHP 读取 JSON 文件并以表格格式显示详细信息。要使用 PHP 函数 file_get_contents (),我们可以读取文件并检索 JSON 文件中存在的数据。取回数据后需要将 JSON 格式转换为数组格式。然后使用循环语句将显示为表格格式。

JSON 输入文件 – 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"}
]

下面的代码将确认 JSON 文件是否存在。如果 JSON 文件不存在,它将显示“未找到 JSON 文件”

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>";
}

使用 foreach 循环获取数组详细信息后,我们将在表格中显示输出

<!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>
输出

慕源网 » 如何使用 PHP 读取 JSON 文件并在表格中显示

常见问题FAQ

程序仅供学习研究,请勿用于非法用途,不得违反国家法律,否则后果自负,一切法律责任与本站无关。
请仔细阅读以上条款再购买,拍下即代表同意条款并遵守约定,谢谢大家支持理解!

发表评论

开通VIP 享更多特权,建议使用QQ登录