PHP 解析非标准拼接JSON数据并转换为CSV的实现方案咨询
PHP处理非标准拼接JSON转CSV实现方案
你当前的JSON属于JSON Lines格式,由多个独立JSON对象拼接而成,无外层数组包裹、对象间无逗号分隔,不符合标准JSON格式规范,因此直接调用json_decode会返回null。以下为两种可行实现方案:
方案1:字符串修正为标准JSON后解码(适合中小数据量)
先通过正则替换把非标准JSON修正为标准JSON数组,再解码处理,代码如下:
<?php $jsondata = '{"firstname": "user1", "lastname": "user1", "phonenumber": "12314", "notes": "[]", "lastvisited": "2021-05-12 21:49:15"} {"firstname": "user2", "lastname": "user2", "phonenumber": "12345", "notes": "[]", "lastvisited": "2021-04-24 20:48:58"}'; // 修正JSON格式:补全数组结构和对象间逗号 $fixedJson = '[' . preg_replace('/\}\s*\{/', '},{', trim($jsondata)) . ']'; $data = json_decode($fixedJson, true); // 校验解析结果 if (json_last_error() !== JSON_ERROR_NONE) { exit('JSON解析失败:' . json_last_error_msg()); } // 生成CSV文件到本地 $csvPath = 'user_data.csv'; $fp = fopen($csvPath, 'w'); // 写入CSV表头 fputcsv($fp, array_keys($data[0])); // 写入每行数据 foreach ($data as $item) { fputcsv($fp, $item); } fclose($fp); // 若需要直接触发浏览器下载,替换生成CSV部分的代码为: /* header('Content-Type: text/csv; charset=utf-8'); header('Content-Disposition: attachment;filename="user_data.csv"'); $fp = fopen('php://output', 'w'); fputcsv($fp, array_keys($data[0])); foreach ($data as $item) { fputcsv($fp, $item); } fclose($fp); exit; */ ?>
方案2:逐行解析JSON(适合大数据量场景)
如果数据量较大,全量加载到内存修正格式性能较低,可以按行切割后逐行解码写入CSV:
<?php $jsondata = '{"firstname": "user1", "lastname": "user1", "phonenumber": "12314", "notes": "[]", "lastvisited": "2021-05-12 21:49:15"} {"firstname": "user2", "lastname": "user2", "phonenumber": "12345", "notes": "[]", "lastvisited": "2021-04-24 20:48:58"}'; $csvPath = 'user_data.csv'; $fp = fopen($csvPath, 'w'); $hasWriteHeader = false; // 按换行切割逐行处理 foreach (explode(PHP_EOL, $jsondata) as $line) { $line = trim($line); if (empty($line)) continue; $item = json_decode($line, true); if (!$item) continue; // 首次写入表头 if (!$hasWriteHeader) { fputcsv($fp, array_keys($item)); $hasWriteHeader = true; } fputcsv($fp, $item); } fclose($fp); ?>
内容的提问来源于stack exchange,提问作者Jayakrishnan Karunanithi
相关产品推荐
相关产品推荐

