
本文介绍如何安全解析从 api 获取的 json 数据,修复常见语法错误,并使用 `json_decode()` 将其转化为可操作的 php 数组,进而按需提取、分类和格式化输出(如 `{l},{100%}` 形式)。
在实际开发中,直接 echo 原始 jsON 响应(尤其是经 gzip 压缩后解码的)不仅难以阅读,还存在严重安全隐患——例如未校验数据完整性、忽略 json 语法错误、缺乏结构化处理逻辑等。你当前的代码:
"()", "format" => "json" )); $result = file_get_contents( '(url)'.$params, false, stream_context_create(array( 'http' => array('method' => 'GET') )) ); echo gzdecode($result); // ❌ 危险:直接输出原始数据,无校验、无解析、无转义 ?>
存在多个关键问题,需逐一解决:
✅ 第一步:修复并验证 JSON 数据源
你提供的示例 JSON 存在 两个致命语法错误:
- “name”: “T } 缺少闭合双引号(应为 “name”: “T”);
- selection12 中嵌套了 selection5 字段,而其他 selection* 均为扁平数组结构,属于数据模型不一致,极可能是服务端 bug 或字段误嵌套。
⚠️ 重要提醒:php 的 json_decode() 在遇到语法错误时会静默返回 NULL($resultArray === null),但不会抛出异常。因此,必须显式检查解码结果:
立即学习“PHP免费学习笔记(深入)”;
$json = gzdecode($result); $resultArray = json_decode($json, true); // 第二个参数 true → 返回关联数组(非对象) if (json_last_error() !== JSON_ERROR_NONE) { throw new RuntimeException('Invalid JSON received: ' . json_last_error_msg()); } if ($resultArray === null) { throw new RuntimeException('JSON decode failed — check for malformed quotes, trailing commas, or encoding issues.'); }
✅ 第二步:结构化提取目标字段
根据你的需求“组织为 {L},{100%}”,即从每个 selectionX 数组中提取首项 name(如 “L”)和次项 name 中的百分比部分(如 “100%nA” → 提取 “100%”),可编写通用解析逻辑:
$parsed = []; foreach ($resultArray as $key => $items) { if (!is_array($items) || count($items) < 2) continue; // 提取第一项 name(如 "L", "S", "H") $label = $items[0]['name'] ?? ''; // 提取第二项 name 并截取百分比(支持 "100%", "100.00%" 等格式) $percentRaw = $items[1]['name'] ?? ''; preg_match('/(d+(?:.d+)?%)/', $percentRaw, $matches); $percent = $matches[1] ?? 'N/A'; $parsed[] = ['label' => $label, 'percent' => $percent]; } // 输出为 {L},{100%} 格式 $output = ''; foreach ($parsed as $item) { $output .= '{' . htmlspecialchars($item['label']) . '},{' . htmlspecialchars($item['percent']) . '}'; } echo $output; // ✅ 安全输出,已转义 HTML 特殊字符
✅ 第三步:增强健壮性与可维护性
- ✨ 使用 curl 替代 file_get_contents:更可控的超时、错误处理与 https 支持;
- ✨ 添加缓存与重试机制:避免频繁请求失败;
- ✨ 定义明确的数据契约(DTO):用类型提示 + assert() 验证结构,例如确保每个 selectionX 是含两个元素的数组;
- ✨ 日志记录异常 JSON 响应体(脱敏后),便于排查上游数据问题。
总结
不要直接 echo 原始响应;始终:
1️⃣ gzdecode() 后立即 json_decode(…, true);
2️⃣ 检查 json_last_error();
3️⃣ 使用 htmlspecialchars() 转义输出,防止 xss;
4️⃣ 按业务逻辑遍历、提取、重组数组,而非字符串正则硬匹配;
5️⃣ 推动 API 提供方修复 JSON 结构一致性问题(如 selection12 的嵌套异常)。
结构清晰、校验完备、输出安全——这才是生产环境 PHP 数据消费的正确姿势。