
在web开发中,经常需要从非数据库的数据源(如文本文件)中读取信息并以结构化的方式展示。本教程将以一个常见的场景为例:从一个包含员工信息的文本文件(name.txt)中读取数据,并将其展示为一个html表格。更进一步,我们不仅展示每条详细记录,还将在表格底部添加一行汇总统计数据,包括唯一姓名数量、总薪资、最常见的城市和平均年龄。
我们的数据源文件name.txt中的每一行都遵循key:value,key:value,...的格式,例如:
name:Ivan,Salary:5000,town:Sofia,age:20 name:Pesho,Salary:1500,town:Pleven,age:19 ...
要实现表格的动态生成和汇总统计,我们需要逐行读取文件,解析每行数据,并将其存储到合适的PHP数组中,以便后续处理。
使用fopen()打开文件,feof()判断文件是否结束,fgets()逐行读取。对于每一行,我们首先使用explode(',', $string)将其按逗号分割成键值对字符串,然后对每个键值对再使用explode(':', $val)按冒号分割成键和值。为了数据清洗,务必使用trim()去除值两端的空白字符。
在遍历文件并输出每行详细数据的同时,我们需要将每条记录中的关键数据(如姓名、薪资、城市、年龄)分别收集到独立的数组中。这是实现汇总统计的关键步骤,因为统计计算需要所有相关数据集合。
立即学习“PHP免费学习笔记(深入)”;
<?php
$file = fopen('name.txt', "r"); // 打开数据文件
// 用于存储所有数据的数组,以便后续进行汇总计算
$names = [];
$cities = [];
$salaries = [];
$ages = [];
echo "<table border=\"1px\">"; // 开始HTML表格
echo "<tr>
<th>Name</th>
<th>Salary</th>
<th>Town</th>
<th>Age</th>
</tr>"; // 表格头部
while (!feof($file)) { // 循环读取文件直到末尾
$string = fgets($file); // 读取一行
if (trim($string) === '') { // 跳过空行
continue;
}
$finalArray = []; // 用于存储当前行解析后的数据
$asArr = explode(',', $string); // 按逗号分割键值对
foreach ($asArr as $val) {
$tmp = explode(':', $val, 2); // 按冒号分割键和值,限制分割次数为2以防值中包含冒号
if (count($tmp) === 2) {
$key = trim($tmp[0]);
$value = trim($tmp[1]);
$finalArray[$key] = $value;
}
}
// 确保所有预期字段都存在,并获取其值
// 使用 null coalescing operator (??) 确保即使字段缺失也不会报错
$name = $finalArray['name'] ?? '';
$salary = (int)($finalArray['Salary'] ?? 0); // 薪资转换为整数
$city = $finalArray['town'] ?? '';
$age = (int)($finalArray['age'] ?? 0); // 年龄转换为整数
// 将当前行的数据添加到各自的收集数组中
$names[] = $name;
$salaries[] = $salary;
$cities[] = $city;
$ages[] = $age;
// 输出当前行的详细数据到表格
echo '<tr>';
echo '<td>' . htmlspecialchars($name) . '</td>';
echo '<td>' . htmlspecialchars($salary) . '</td>';
echo '<td>' . htmlspecialchars($city) . '</td>';
echo '<td>' . htmlspecialchars($age) . '</td>';
echo '</tr>';
}
// 文件读取完毕,关闭文件句柄
fclose($file);
?>在所有数据行都已输出并且数据收集完毕后,我们就可以对收集到的数组进行统计计算,并将其作为表格的最后一行输出。
将计算出的统计值作为新的<tr>中的<td>元素输出。
<?php
// ... (接上一段代码)
// 计算汇总统计数据
$countOfUniqueNames = count(array_unique($names)); // 唯一姓名数量
$sumOfAllSalaries = array_sum($salaries); // 总薪资
$citiesCount = array_count_values($cities); // 统计每个城市出现的次数
$maxVal = 0;
$mostCommonCity = 'N/A';
if (!empty($citiesCount)) {
$maxVal = max($citiesCount); // 最多出现的次数
$mostCommonCity = array_search($maxVal, $citiesCount); // 对应最多次数的城市
}
$averageAges = 0;
if (!empty($ages)) {
$averageAges = (int)(array_sum($ages) / count($ages)); // 平均年龄
}
// 输出汇总行
echo '<tr>';
echo '<td><strong>唯一姓名数: ' . htmlspecialchars($countOfUniqueNames) . '</strong></td>';
echo '<td><strong>总薪资: ' . htmlspecialchars($sumOfAllSalaries) . '</strong></td>';
echo '<td><strong>最常见城市: ' . htmlspecialchars($mostCommonCity) . '</strong></td>';
echo '<td><strong>平均年龄: ' . htmlspecialchars($averageAges) . '</strong></td>';
echo '</tr>';
echo "</table>"; // 结束HTML表格
?>将上述所有代码片段组合起来,形成一个完整的PHP脚本。
<?php
// 假设 name.txt 文件内容如下:
// name:Ivan,Salary:5000,town:Sofia,age:20
// name:Pesho,Salary:1500,town:Pleven,age:19
// name:Gosho,Salary:2000,town:Varna,age:18
// name:Georgi,Salary:3000,town:Pleven,age:46
// name:Ivailo,Salary:6000,town:Pleven,age:25
// name:Stamat,Salary:7000,town:Varna,age:46
// name:Aleksandar,Salary:1500,town:Burgas,age:44
// name:Kiko,Salary:5000,town:Plovdiv,age:25
// name:Misho,Salary:5250,town:Sofia,age:24
// name:Daniel,Salary:3000,town:Plovdiv,age:34
// name:John,Salary:6000,town:Pleven,age:50
// name:Ana,Salary:9000,town:Sofia,age:18
// name:Maria,Salary:9500,town:Sofia,age:30
// name:Marian,Salary:9500,town:Sofia,age:20
// name:Petko,Salary:9500,town:Sofia,age:19
// name:Nikola,Salary:9500,town:Sofia,age:45
// name:Ani,Salary:9500,town:Sofia,age:47
$filePath = 'name.txt';
// 检查文件是否存在且可读
if (!file_exists($filePath) || !is_readable($filePath)) {
die("错误:文件 '$filePath' 不存在或无法读取。");
}
$file = fopen($filePath, "r");
if (!$file) {
die("错误:无法打开文件 '$filePath'。");
}
// 用于存储所有数据的数组,以便后续进行汇总计算
$names = [];
$cities = [];
$salaries = [];
$ages = [];
echo "<!DOCTYPE html>
<html lang=\"zh-CN\">
<head>
<meta charset=\"UTF-8\">
<title>员工数据统计</title>
<style>
table {
width: 100%;
border-collapse: collapse;
}
th, td {
border: 1px solid #ddd;
padding: 8px;
text-align: left;
}
th {
background-color: #f2f2f2;
}
tr:last-child {
font-weight: bold;
background-color: #e0e0e0;
}
</style>
</head>
<body>";
echo "<h2>员工信息及统计</h2>";
echo "<table border=\"1px\">";
echo "<thead>";
echo "<tr>
<th>姓名</th>
<th>薪资</th>
<th>城市</th>
<th>年龄</th>
</tr>";
echo "</thead>";
echo "<tbody>";
while (!feof($file)) {
$string = fgets($file);
if ($string === false) { // 检查 fgets 是否返回 false (文件读取错误或结束)
break;
}
$string = trim($string); // 去除行尾空白符和换行符
if ($string === '') { // 跳过空行
continue;
}
$finalArray = [];
$asArr = explode(',', $string);
foreach ($asArr as $val) {
$tmp = explode(':', $val, 2); // 限制分割次数为2,以防值中包含冒号
if (count($tmp) === 2) {
$key = trim($tmp[0]);
$value = trim($tmp[1]);
$finalArray[$key] = $value;
}
}
// 从解析后的数组中提取数据,并进行类型转换和默认值处理
$name = $finalArray['name'] ?? '';
$salary = (int)($finalArray['Salary'] ?? 0); // 薪资确保为整数
$city = $finalArray['town'] ?? '';
$age = (int)($finalArray['age'] ?? 0); // 年龄确保为整数
// 将当前行的数据添加到各自的收集数组中
$names[] = $name;
$salaries[] = $salary;
$cities[] = $city;
$ages[] = $age;
// 输出当前行的详细数据到表格
echo '<tr>';
echo '<td>' . htmlspecialchars($name) . '</td>';
echo '<td>' . htmlspecialchars($salary) . '</td>';
echo '<td>' . htmlspecialchars($city) . '</td>';
echo '<td>' . htmlspecialchars($age) . '</td>';
echo '</tr>';
}
fclose($file); // 关闭文件句柄
// 计算汇总统计数据
$countOfUniqueNames = count(array_unique($names));
$sumOfAllSalaries = array_sum($salaries);
$citiesCount = array_count_values($cities);
$mostCommonCity = 'N/A';
if (!empty($citiesCount)) {
$maxVal = max($citiesCount);
$mostCommonCity = array_search($maxVal, $citiesCount);
}
$averageAges = 0;
if (!empty($ages)) {
$averageAges = (int)(array_sum($ages) / count($ages));
}
// 输出汇总行
echo '<tr>';
echo '<td><strong>唯一姓名数: ' . htmlspecialchars($countOfUniqueNames) . '</strong></td>';
echo '<td><strong>总薪资: ' . htmlspecialchars($sumOfAllSalaries) . '</strong></td>';
echo '<td><strong>最常见城市: ' . htmlspecialchars($mostCommonCity) . '</strong></td>';
echo '<td><strong>平均年龄: ' . htmlspecialchars($averageAges) . '</strong></td>';
echo '</tr>';
echo "</tbody>";
echo "</table>";
echo "</body>
</html>";
?>本教程详细演示了如何使用PHP从结构化的文本文件中读取、解析数据,并将其动态呈现在一个HTML表格中。通过在数据读取过程中同步收集必要信息,我们成功地在表格底部添加了有用的汇总统计行。这种模式在处理日志文件、CSV文件或其他自定义格式数据时非常实用,为数据展示和初步分析提供了便捷的解决方案。
以上就是PHP从文本文件解析数据并生成带汇总行的HTML表格教程的详细内容,更多请关注php中文网其它相关文章!
HTML怎么学习?HTML怎么入门?HTML在哪学?HTML怎么学才快?不用担心,这里为大家提供了HTML速学教程(入门课程),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号