Skip to content

Instantly share code, notes, and snippets.

@t1maccapp
Forked from Kostanos/json-to-csv.php
Created October 26, 2015 22:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save t1maccapp/257a42dc88ba3c1eb017 to your computer and use it in GitHub Desktop.
Save t1maccapp/257a42dc88ba3c1eb017 to your computer and use it in GitHub Desktop.
Convert JSON array file to CSV. Use the array keys as the first row. Command line using: json-to-csv.php json.filename > csv.filename
#!/usr/bin/php
<?php
/*
* Convert JSON file to CSV and output it.
*
* JSON should be an array of objects, dictionaries with simple data structure
* and the same keys in each object.
* The order of keys it took from the first element.
*
* Example:
* json:
* [
* { "key1": "value", "kye2": "value", "key3": "value" },
* { "key1": "value", "kye2": "value", "key3": "value" },
* { "key1": "value", "kye2": "value", "key3": "value" }
* ]
*
* The csv output: (keys will be used for first row):
* 1. key1, key2, key3
* 2. value, value, value
* 3. value, value, value
* 4. value, value, value
*
* Uses:
* json-to-csv.php file.json > file.csv
*/
if (empty($argv[1])) die("The json file name or URL is missed\n");
$jsonFilename = $argv[1];
$json = file_get_contents($jsonFilename);
$array = json_decode($json, true);
$f = fopen('php://output', 'w');
$firstLineKeys = false;
foreach ($array as $line)
{
if (empty($firstLineKeys))
{
$firstLineKeys = array_keys($line);
fputcsv($f, $firstLineKeys);
$firstLineKeys = array_flip($firstLineKeys);
}
// Using array_merge is important to maintain the order of keys acording to the first element
fputcsv($f, array_merge($firstLineKeys, $line));
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment