-
-
Save rafialikhan/05908e5e915424fea8b5c36939faabfc to your computer and use it in GitHub Desktop.
Convert Firebase JSON array file to CSV.Use the array keys as the first row. Command line using: PHP firebase-json-to-csv.php filename.json > filename.csv
This file contains hidden or 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
#!/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. | |
* | |
* Since firebase has an object of objects (serialized) - we need to convert it to an array | |
* Example: | |
* json: | |
* { | |
* "colleges":{ | |
* { "address": "value", "name": "value", "website": "value" }, | |
* { "address": "value", "name": "value", "website": "value" }, | |
* { "address": "value", "name": "value", "website": "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]; | |
$jsonObj = file_get_contents($jsonFilename); | |
$array = json_decode($jsonObj, true); | |
//*******Change colleges to whatever your key object from firebase - basically converting the object of objects to an array of objects | |
$array = $array["colleges"]; | |
$array = array_values($array); | |
$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
PHP Notice: Array to string conversion in json_csv.php on line 48