将JSON转换为CSV并从浏览器保存到计算机

时间:2015-05-15 22:46:43

标签: php json csv export-to-excel

我有这个JSON:

{"data":[{"ID":1,"br":"1-2015","kupac":"ADAkolor","datum":"2015-05-19","rok":"2015-05-21","status":"placeno"},{"ID":2,"br":"2-2015","kupac":"Milenk","datum":"2015-05-27","rok":"2015-05-28","status":""}]}

如何使用php pdo将其转换为CSV文件或Exel XLS?

同样在这个例子中:

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));
}

我需要把我的$ jsonTable放在哪里?

2 个答案:

答案 0 :(得分:1)

使用JSON2CSV

  

将JSON数据转换为CSV的简单PHP脚本

示例用法:

php json2csv.php --file=/path/to/source/file.json --dest=/path/to/destination/file.csv

或者您可以让它转储相对于PHP脚本的CSV文件:

php json2csv.php --file=/path/to/source/file.json

答案 1 :(得分:0)

我不确定pdo部分,但要将它写入文件,你会做这样的事情

$json = '{"data":[{"ID":1,"br":"1-2015","kupac":"ADAkolor","datum":"2015-05-19","rok":"2015-05-21","status":"placeno"},{"ID":2,"br":"2-2015","kupac":"Milenk","datum":"2015-05-27","rok":"2015-05-28","status":""}]}';

$out = fopen('file.csv', 'w');
foreach(json_decode($json, true)['data'] as $key => $value) {
  fputcsv($out, $value);
}
fclose($out);