如何将PHP foreach遍历得到的变量输出展示到HTML表格中
解决方案
你之前输出失败的核心原因有两个:
- 在PHP的echo语句内嵌套了
<?php ?>标签,属于语法错误,解析器无法正常识别输出内容 - 缺少完整的HTML表格结构,单独输出
<td>标签没有对应的<table>、<tr>等父标签包裹,不会渲染为表格内容
修正后可直接运行的完整代码
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <style> table { border-collapse: collapse; width: 90%; margin: 20px 0; } th, td { border: 1px solid #eee; padding: 10px; text-align: left; } th { background-color: #f5f5f5; } </style> </head> <body> <?php session_start(); $curl_handle = curl_init(); curl_setopt($curl_handle, CURLOPT_URL, 'https://services-ap1.arcgis.com/YQyt7djuXN7rQyg4/arcgis/rest/services/Historical_ParksList_2017/FeatureServer/0/query?where=1%3D1&outFields=*&outSR=4326&f=json'); curl_setopt($curl_handle, CURLOPT_CONNECTTIMEOUT, 2); curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER, 1); $buffer = curl_exec($curl_handle); curl_close($curl_handle); if (empty($buffer)) { print "数据获取失败,请稍后重试"; } else { $json = json_decode($buffer, true); $info = $json["features"]; $total = count($info); print "数据获取成功<br>查询到结果总数:" . $total . "<br><hr style='height: 2px;'>"; // 输出表格头部 echo '<table> <thead> <tr> <th>公园名称</th> <th>所属郊区</th> <th>具体位置</th> <th>配套设施</th> </tr> </thead> <tbody>'; foreach ($info as $item) { // 处理字段空值 $parkName = empty($item["attributes"]["name"]) ? "未收录" : $item["attributes"]["name"]; $suburb = empty($item["attributes"]["suburb"]) ? "未收录" : $item["attributes"]["suburb"]; $location = empty($item["attributes"]["location"]) ? "未收录" : $item["attributes"]["location"]; $facilities = empty($item["attributes"]["facilities"]) ? "未收录" : $item["attributes"]["facilities"]; // 输出单条数据行 echo "<tr> <td>{$parkName}</td> <td>{$suburb}</td> <td>{$location}</td> <td>{$facilities}</td> </tr>"; // 如果有其他页面需要用到session存储数据,可自行在这里添加对应session赋值代码 } // 闭合表格标签 echo '</tbody></table>'; } ?> </body> </html>
代码说明
- 加了基础的表格样式,你后续要加搜索、筛选功能可以直接基于这个表格结构开发
- 用三目运算符简化了空值判断逻辑,代码更精简易读
- 所有变量直接在echo语句内输出,不需要嵌套PHP标签
- 加了UTF-8编码声明,避免中文乱码
内容的提问来源于stack exchange,提问作者Angus Webb
相关产品推荐
相关产品推荐

