我想用php腳本將json文件轉換爲csv格式。代碼如下:使用PHP將JSON轉換爲CSV格式
if (empty($argv[1])) die("The json file name or URL is missed\n");
$jsonFilename = $argv[1];
$json = file_get_contents($jsonFilename);
$array = json_decode($json, true);
$f = fopen('output.csv', 'w');
$firstLineKeys = false;
foreach ($array as $line)
{
if (empty($firstLineKeys))
{
$firstLineKeys = array_keys($line);
fputcsv($f, $firstLineKeys);
$firstLineKeys = array_flip($firstLineKeys);
}
fputcsv($f, array_merge($firstLineKeys, $line));
}
這類作品,但只返回JSON文件的外部變量,我得到一個「陣列字符串轉換」警告
JSON數據是這樣的:
{"type":"NON_ATTRIBUTED","conversion":{,"value_1":"000000100355321","value_3":"XXXX","value_4":"12667","value_5":"6"},"stream_type":"COOKIE"}
{"type":"ATTRIBUTED","conversion":{,"value_1":"000000167865321","value_3":"YYYY","value_4":"12668","value_5":"0"},"stream_type":"COOKIE"}
{"type":"NON_ATTRIBUTED","conversion":{,"value_1":"000000134535321","value_3":"AAAA","value_4":"12669","value_5":"9"},"stream_type":"COOKIE"}
{"type":"NON_ATTRIBUTED","conversion":{,"value_1":"000000100357651","value_3":"WWWW","value_4":"12670","value_5":"2"},"stream_type":"COOKIE"}
我得到的輸出是: 型,轉換,流_ NON_ATTRIBUT ED,陣列,COOKIE NON_ATTRIBUTED,陣列,COOKIE
我期待的輸出是: 類型,轉換,_1,VALUE_3,VALUE_4,VALUE_5,的stream_type NON_ATTRIBUTED,000000100355321,XXXX,1267,6,COOKIE 。 。
理解,因爲任何幫助,這是非常新的我
這是完美的!非常感謝:) – user2647092
@Applejack對於'if(empty($ firstLineKeys))'''firstLineKeys'是否必須爲true,因此'if'循環中的語句才能運行? – pHorseSpec
@pHorseSpec這條線與問題本身無關,所以我沒有改變它。如果您需要將某些JSON轉換爲CSV,則首先應決定CSV文件的結構,因爲JSON和CSV是不同的數據結構:JSON是樹,CSV是表格。主題開始構建自己的結構,但他在代碼和JSON文件中出現錯誤,所以我所做的只是修復了它。 –