Skip to content

Instantly share code, notes, and snippets.

@m-manu
Created August 4, 2015 06:45
Show Gist options
  • Save m-manu/c2313329c4dd509554be to your computer and use it in GitHub Desktop.
Save m-manu/c2313329c4dd509554be to your computer and use it in GitHub Desktop.
Attempts to convert a JSON to CSV
<?php
if (count($argv) != 3) {
error_log("Pass input_file_path output_file_path");
exit;
}
$input_file_path = $argv[1];
$output_file_path = $argv[2];
$json_str = file_get_contents($input_file_path);
$json = json_decode($json_str, true);
function json2csv(array $json, $output_file_path) {
$f = fopen($output_file_path, "w");
$keys = array_keys($json[0]);
for ($i = 0; $i < count($json); $i++) {
$record = $json[$i];
$row = array();
for ($j = 0; $j < count($keys); $j++) {
$row[] = $record[$keys[$j]];
}
fputcsv($f, $row);
}
fclose($f);
}
$int_index_json = array_values($json);
if ($json == $int_index_json) {
json2csv($json, $output_file_path);
}
elseif (count($json) > 0 && is_array($int_index_json[0]) && $int_index_json[0] == array_values($int_index_json[0])) {
json2csv($int_index_json[0], $output_file_path);
}
else {
error_log("unsupported json format for csv conversion");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment