Skip to content

Instantly share code, notes, and snippets.

@Guitlle
Last active March 6, 2018 23:46
Show Gist options
  • Save Guitlle/2edc08b450ea6f57b463b94da05efb9d to your computer and use it in GitHub Desktop.
Save Guitlle/2edc08b450ea6f57b463b94da05efb9d to your computer and use it in GitHub Desktop.
Convert a list of json strings to csv in PHP
<?php
/*
author: Guillermo <yo@guilles.website>
This converst a list of jsons to a csv string. JSON names
are built with the key names and points. See example below.
It basically flattens associative arrays with a recursive function
and then merges all these flattened arrays.
*/
function jsonListToCSV ($jsonList) {
function procArray(&$input, &$output, $path) {
foreach ($input as $key => $val) {
if (is_array($val)) {
procArray($input[$key], $output, empty($path) ? $key : $path.".".$key);
}
else {
$output[empty($path)? $key : $path.".".$key] = $val;
}
}
}
$flatDatas = array();
$keys = array();
foreach ($jsonList as $record) {
$data = json_decode($record, TRUE);
$flatData = array();
procArray($data, $flatData, "");
array_push($flatDatas, $flatData);
$keys = array_merge($keys, array_diff(array_keys($flatData), $keys));
}
sort($keys, SORT_STRING);
$csvoutput = implode(",", $keys)."\n\r";;
$nkeys = count($keys);
foreach ($flatDatas as $flatData) {
$i = 0;
foreach($keys as $key) {
$i++;
if (isset($flatData[$key])) {
$csvoutput .= "\"".addslashes($flatData[$key])."\"";
}
else {
$csvoutput .= "";
}
if ($i < $nkeys)
$csvoutput .= ",";
}
$csvoutput .= "\n\r";
}
return $csvoutput;
}
/*
EXAMPLE:
echo jsonListToCSV(array(
'{ "a": 1, "b": { "c": 2, "d": [3,4,5,6] } }',
'{ "a": 5, "b": { "c": 6, "d": [7,8] }, "f": [ {"g": 9}, {"h": 10} ] }',
'{ "b": { "c": 7, "d": [9,10,11] }, "f": [ {"g": 9}, {"g": 10} ] }',
'{ "a": 6, "b": { "c": 8, "d": [72,18] }, "f": [ {"g": 19}, {"g": 15} ] }',
'{ "a": 7, "b": { "c": 9, "d": [17,98,10] }, "f": [ {"g": 92}, {"h": 1} ] }',
));
OUTPUT:
a,b.c,b.d.0,b.d.1,b.d.2,b.d.3,f.0.g,f.1.g,f.1.h
"1","2","3","4","5","6",,,
"5","6","7","8",,,"9",,"10"
,"7","9","10","11",,"9","10",
"6","8","72","18",,,"19","15",
"7","9","17","98","10",,"92",,"1"
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment