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


Convert JSON to CSV and save from browser to computer

我有这个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":""}]}

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

同样在这个例子中:

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 ?

使用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

我不确定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);