You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用PHP将URL返回的JSON数组数据循环渲染为HTML表格

修复后的代码及说明

原有代码存在的问题

  • 设备列表遍历逻辑错误:for循环终止条件未获取数组长度,且固定读取索引0的元素,仅能输出第一个装备
  • HTML结构错误:行闭合标签</tr>放在了车辆遍历循环外部,导致表格结构失效
  • 图片遍历逻辑同样存在固定读取索引0的问题,仅能展示第一张图片
  • 动态生成多个装备、图片单元格会导致列数和表头不匹配,建议把同一条车辆的所有装备放在同一个单元格内展示

可直接运行的修复后代码

<?php
$url = 'https://gw.bilinfo.net/listingapi/api/export';

// 此处填写你的账号密码
$auth = base64_encode("demo:ocfB6XzF73");

// 生成带基础认证的HTTP上下文
$context = stream_context_create([
    'http' => ['header' => "Authorization: Basic $auth"]
]);

// 请求接口数据
$data = file_get_contents($url, false, $context);
$escaped = json_decode($data);

// 初始化表格变量
$temp = "<table border='1' cellpadding='8' cellspacing='0'>";

// 定义表头
$temp .= "<tr>";
$temp .= "<th>品牌</th>";
$temp .= "<th>型号</th>";
$temp .= "<th>发动机</th>";
$temp .= "<th>燃料类型</th>";
$temp .= "<th>装备清单</th>";
$temp .= "<th>车辆图片</th>";
$temp .= "</tr>";

// 动态生成表格行
foreach ($escaped->Vehicles as $vehicle) {
    $temp .= "<tr>";
    $temp .= "<td>" . htmlspecialchars($vehicle->Make) . "</td>";
    $temp .= "<td>" . htmlspecialchars($vehicle->Model) . "</td>";
    $temp .= "<td>" . htmlspecialchars($vehicle->Motor) . "</td>";
    $temp .= "<td>" . htmlspecialchars($vehicle->Propellant) . "</td>";

    // 拼接所有装备到同一个单元格,用顿号分隔
    $equipmentStr = implode('、', $vehicle->EquipmentList);
    $temp .= "<td>" . htmlspecialchars($equipmentStr) . "</td>";

    // 拼接所有图片到同一个单元格
    $pictureStr = '';
    foreach ($vehicle->Pictures as $pic) {
        $pictureStr .= "<img src='" . htmlspecialchars($pic) . "' width='100' style='margin-right: 5px;' />";
    }
    $temp .= "<td>" . $pictureStr . "</td>";
    // 闭合当前行
    $temp .= "</tr>";
}

// 闭合表格
$temp .= "</table>";

// 输出表格
echo $temp;
?>

额外优化点

  • 新增了htmlspecialchars转义输出内容,避免XSS安全问题
  • 给表格加了边框、内边距样式,显示效果更好
  • 图片限制了宽度,避免撑破表格

内容的提问来源于stack exchange,提问作者Martin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 12:36:03