2012-03-05 98 views
6

我有一個JSON服務,需要創建一個腳本來將數據導出到CSV文件。有沒有人有建議將JSON遷移到CSV格式的方法或庫?PHP庫將JSON轉換爲CSV?

這裏有一個例子格式雖然我期望有復古適合的解決方案與它的工作:

{"service_name": 
     { key : value, key : value....} 
} 

或:

{"service_name": 
     [ 
       { key : value, key : value....}, 
       ... 
     ] 
} 
+1

你可以做[這個問題]的反轉(http://stackoverflow.com/questions/4811844/csv-to-json-with-php)? – 2012-03-05 20:24:38

+5

JSON的結構是什麼? JSON可以有一個非常複雜的嵌套結構,可能無法將其有意義地渲染爲csv。 – Chris 2012-03-05 20:25:14

+0

http://stackoverflow.com/questions/4811844/csv-to-json-with-php – 2012-03-05 20:25:35

回答

9

我大體上同意提意見,但如果你'數據是這樣準備的,是不是你需要的這個僞代碼?

$json_str = "{'aintlist':[4,3,2,1], 'astringlist':['str1','str2']}"; 

$json_obj = json_decode ($json_str); 

$fp = fopen('file.csv', 'w'); 

foreach ($json_obj as $fields) { 
    fputcsv($fp, $fields); 
} 

fclose($fp); 
+1

在我的情況下,我會在字段上施放(數組)。 PHP 5.3。 – 2013-09-02 13:51:41

1

像這樣的事情應該工作,假設您的JSON是數據集,而不陣列或嵌入對象的數組:

$file = file_get_contents('http://example.com/blah/blah'); 
$json = json_decode($file); 

$csvfile = fopen('file.csv', 'w+'); 
foreach ($json as $row) { 
    $line = "'" . join("\",\"", $row) . "\"\n"; 
    fputs($csvfile, $line); 
} 
fclose($csvfile); 

你必須添加相應的錯誤處理。有很多東西在嘗試做這類事情時可能會出錯(即JSON文件不可用或格式不正確,無法創建新的CSV文件)

1

我只需要做同樣的事情。我編寫了一個小命令行腳本,它將json文件作爲參數並輸出CSV。

您可以點擊此處查看:PHP Converting JSON array to CSV

重要的人員有使用數組作爲CSV文件的第一行的鍵。 並維護下一個元素的順序,以免搞亂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('php://output', 'w'); 

$firstLineKeys = false; 
foreach ($array as $line) 
{ 
    if (empty($firstLineKeys)) 
    { 
     $firstLineKeys = array_keys($line); 
     fputcsv($f, $firstLineKeys); 
     $firstLineKeys = array_flip($firstLineKeys); 
    } 
    // Using array_merge is important to maintain the order of keys acording to the first element 
    fputcsv($f, array_merge($firstLineKeys, $line)); 
}