Created
August 24, 2013 18:25
-
-
Save lfbittencourt/6329646 to your computer and use it in GitHub Desktop.
JSON to CSV converter.
This file contains 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 | |
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