2012-03-05 133 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)); 
}