本文介绍如何安全解析从 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 存在 两个致命语法错误:
⚠️ 重要提醒:PHP 的 json_decode() 在遇到语法错误时会静默返回 null($resultArray === null),但不会抛出异常。因此,必须显式检查解码结果:
$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 特殊字符不要直接 echo 原始响应;始终:
1️⃣ gzdecode() 后立即 json_decode(..., true);
2️⃣ 检查 json_last_error();
3️⃣ 使用 htmlspecialchars() 转义输出,防止 XSS;
4️⃣ 按业务逻辑遍历、提取、重组数组,而非字符串正则硬匹配;
5️⃣ 推动 API 提供方修复 JSON 结构一致性问题(如 selection12 的嵌套异常)。
结构清晰、校验完备、输出安全——这才是生产环境 PHP 数据消费的正确姿势。