Skip to content

Instantly share code, notes, and snippets.

@nirbhabbarat
Forked from jpswade/json2csv.php
Created November 1, 2020 10:07
Show Gist options
  • Save nirbhabbarat/ec09ea29c88817f7f59c28a5c96adc3c to your computer and use it in GitHub Desktop.
Save nirbhabbarat/ec09ea29c88817f7f59c28a5c96adc3c to your computer and use it in GitHub Desktop.
convert from a multi-dimensional json object to a flat csv table
<?php
/**
* @param string $jsonFilename
* @param string $csvFilename
* @return bool|int
*/
function json2csv($jsonFilename, $csvFilename)
{
$json = file_get_contents($jsonFilename);
$data = json_decode($json, true);
$fp = fopen($csvFilename, 'w');
$keys = [];
foreach ($data as $row) {
foreach ($row as $key => $value) {
$keys[] = $key;
}
}
$header = array_unique($keys);
$len = fputcsv($fp, $header);
foreach ($data as $row) {
foreach ($row as $key => $value) {
if (is_array($value)) {
$row[$key] = empty($value) ? null : json_encode($value);
}
}
$fields = [];
foreach ($header as $key) {
$fields[$key] = isset($row[$key]) ? $row[$key] : null;
}
$len += fputcsv($fp, $fields);
}
fclose($fp);
return $len;
}
echo json2csv($argv[1], $argv[2]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment