Skip to content

Instantly share code, notes, and snippets.

@lfbittencourt
Created August 24, 2013 18:25
Show Gist options
  • Save lfbittencourt/6329646 to your computer and use it in GitHub Desktop.
Save lfbittencourt/6329646 to your computer and use it in GitHub Desktop.
JSON to CSV converter.
<?php
if ($argc < 2) {
echo 'Usage: json2csv.php [input.json] output.csv', PHP_EOL;
exit(1);
}
$input = fopen($argc === 3 ? $argv[1] : 'php://stdin', 'r');
if ($input === false) {
echo 'Invalid input.', PHP_EOL;
exit(2);
}
$json = '';
while (!feof($input)) {
$json .= fread($input, 1024);
}
fclose($input);
$data = json_decode($json);
$output = fopen(array_pop($argv), 'w');
foreach ($data as $fields) {
fputcsv($output, (array) $fields);
}
fclose($output);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment