Created
March 11, 2020 14:43
-
-
Save jpswade/dd0c51c94704dfaa2fcf3b38502add51 to your computer and use it in GitHub Desktop.
convert from a multi-dimensional json object to a flat csv table
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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