使用PHP将JSON从URL转换为CSV

时间:2017-08-14 20:24:06

标签: php json csv

当我运行下面的代码时,会导致列的长列表中的第一行只包含文本 Array

我已经使用Start Wifi Bridge Session... Send UDP commands to 192.168.1.13 port 5987 Sent: 20 00 00 00 16 02 62 3A D5 ED A3 01 AE 08 2D 46 61 41 A7 F6 DC AF D3 E6 00 00 1E Received: 28 00 00 00 11 00 02 F0 FE 6B 26 28 16 14 CA 43 76 00 01 08 00 00 LimitlessLEDWifiBridgeSessionID1 is 08 LimitlessLEDWifiBridgeSessionID2 is 00 IP Address is 192.168.1.13 MAC Address is FE:6B:26:28:16:14 Sequence Number is 02 Checksum is 3E Sent: 80 00 00 00 11 08 00 00 02 00 31 00 00 08 04 01 00 00 00 00 00 3E Command SUCCESSFUL. Received: 88 00 00 00 03 00 02 00 Command completed. 表示我需要数组而不是对象,因此我不确定问题是什么。

我是否应该在某处使用括号或箭头符号来指定我想要数组值?

$decoded = json_decode($json_file, true);

这是一小段JSON。它看起来像这样:

$json_file = file_get_contents('https://fakeurl.com&contentType=json', false);

$decoded = json_decode($json_file, true);

$fp = fopen('output.csv', 'w');
foreach($decoded as $comment) {
    fputcsv($fp, $comment);
}
fclose($fp);

1 个答案:

答案 0 :(得分:4)

您的数组更深,需要提取值:

foreach($decoded['rows'] as $row) {
    $values = array_column($row['columns'], 'value');
    fputcsv($fp, $values);
}

如果您想要第一行中的名称/标题,那么您需要在循环之前执行此操作:

$headers = array_column($decoded['rows'][0]['columns'], 'name');
fputcsv($fp, $headers);