Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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));
}
?>
@Charl13

This comment has been minimized.

Copy link

Charl13 commented Nov 25, 2013

Works like a charm, thanks!

@saloni12

This comment has been minimized.

Copy link

saloni12 commented Feb 7, 2014

please advise..what comes in place of the red lines. I am not a programmer and really need help.

@saloni12

This comment has been minimized.

Copy link

saloni12 commented Feb 7, 2014

all i get as the out is The json file name or URL is missed!!!!

@mwalol

This comment has been minimized.

Copy link

mwalol commented May 28, 2014

array_keys() expects parameter 1 to be array, string given in convert.php on line 40

json input

from facebook

{
"id": "15606624099",
"first_name": "Abdpel",
"gender": "male",
"last_name": "El Gulessab",
"locale": "fr_FR",
"name": "Abdel El Guessab",
"username": "zdd.elguessab"
}

@drorata

This comment has been minimized.

Copy link

drorata commented Jul 17, 2014

Seems to work perfectly!!! Thank.

@dael

This comment has been minimized.

Copy link

dael commented Nov 25, 2014

Thanks for your work

@SniperRus

This comment has been minimized.

Copy link

SniperRus commented Dec 23, 2014

great! work fast.
how can filter some raw with some expression? for exp. - gender=male and locale=fr_FR?

@btn15

This comment has been minimized.

Copy link

btn15 commented Jan 28, 2015

Error:
Warning: Invalid argument supplied for foreach()

@jakebathman

This comment has been minimized.

Copy link

jakebathman commented Mar 2, 2015

Created a fork to make this a PHP function that can be included in other PHP files.

Here's the new gist: https://gist.github.com/jakebathman/4fb8c55b13272eee9c88

The new function jsonToCsv has a few new options, including outputting the CSV file to the browser or echoing the CSV string to the browser window.

Thanks for the good foundation!

@t1maccapp

This comment has been minimized.

Copy link

t1maccapp commented Oct 26, 2015

Ok, if you see an error "Fatal error: Allowed memory size of 536870912 bytes exhausted (tried to allocate 32 bytes) in ..." just add this line after comments block and specify amount of ram you need.

ini_set('memory_limit', '512M');

Also if you have an error like "Error: Warning: Invalid argument supplied for foreach()" try to validate your json file. I used this https://www.npmjs.com/package/jsonlint (It worked with 100+ MB json file)

And if you have troubles trying to convert json file from mongoexport and it fails then check this link http://stackoverflow.com/questions/28206472/bson-produced-by-mongoexport-from-mongodb-is-not-a-valid-json

btw, thanks for this script

@elazdins

This comment has been minimized.

Copy link

elazdins commented Aug 3, 2016

Thanks for this! Modified the script to work with variable length json entries:

https://gist.github.com/elazdins/a2cfbea9c23fd039e680602de5133a34

@clesauln

This comment has been minimized.

Copy link

clesauln commented Jun 26, 2018

Thanks, i have adapted this converter to parse Point and properties to csv

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.