Skip to content

Instantly share code, notes, and snippets.

@jakebathman
Forked from Kostanos/json-to-csv.php
Last active June 5, 2022 21:02
Show Gist options
  • Star 21 You must be signed in to star a gist
  • Fork 9 You must be signed in to fork a gist
  • Save jakebathman/4fb8c55b13272eee9c88 to your computer and use it in GitHub Desktop.
Save jakebathman/4fb8c55b13272eee9c88 to your computer and use it in GitHub Desktop.
A function to convert a JSON string (or a PHP array) to a CSV file or CSV string echoed to the browser
<?php
/*
*
* Based on (forked from) the work by https://gist.github.com/Kostanos
*
* This revision allows the PHP file to be included/required in another PHP file and called as a function, rather than focusing on command line usage.
*
* 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
*
* Usage:
*
* require '/path/to/json-to-csv.php';
*
* // echo a JSON string as CSV
* jsonToCsv($strJson);
*
* // echo an arrayJSON string as CSV
* jsonToCsv($arrJson);
*
* // save a JSON string as CSV file
* jsonToCsv($strJson,"/save/path/csvFile.csv");
*
* // save a JSON string as CSV file through the browser (no file saved on server)
* jsonToCsv($strJson,false,true);
*
*
*/
function jsonToCsv ($json, $csvFilePath = false, $boolOutputFile = false) {
// See if the string contains something
if (empty($json)) {
die("The JSON string is empty!");
}
// If passed a string, turn it into an array
if (is_array($json) === false) {
$json = json_decode($json, true);
}
// If a path is included, open that file for handling. Otherwise, use a temp file (for echoing CSV string)
if ($csvFilePath !== false) {
$f = fopen($csvFilePath,'w+');
if ($f === false) {
die("Couldn't create the file to store the CSV, or the path is invalid. Make sure you're including the full path, INCLUDING the name of the output file (e.g. '../save/path/csvOutput.csv')");
}
}
else {
$boolEchoCsv = true;
if ($boolOutputFile === true) {
$boolEchoCsv = false;
}
$strTempFile = 'csvOutput' . date("U") . ".csv";
$f = fopen($strTempFile,"w+");
}
$firstLineKeys = false;
foreach ($json 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));
}
fclose($f);
// Take the file and put it to a string/file for output (if no save path was included in function arguments)
if ($boolOutputFile === true) {
if ($csvFilePath !== false) {
$file = $csvFilePath;
}
else {
$file = $strTempFile;
}
// Output the file to the browser (for open/save)
if (file_exists($file)) {
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename='.basename($file));
header('Content-Length: ' . filesize($file));
readfile($file);
}
}
elseif ($boolEchoCsv === true) {
if (($handle = fopen($strTempFile, "r")) !== FALSE) {
while (($data = fgetcsv($handle)) !== FALSE) {
echo implode(",",$data);
echo "<br />";
}
fclose($handle);
}
}
// Delete the temp file
unlink($strTempFile);
}
?>
@drequeceler
Copy link

Thank you!

@izuro
Copy link

izuro commented Mar 17, 2015

Brilliant, thank you!

@koofah
Copy link

koofah commented Jun 2, 2016

May God Bless u . Thanks.

@SDJeff
Copy link

SDJeff commented Jun 11, 2016

I think there two improvements:

  1. Line 65: $boolEchoCsv = false; otherwise it isn't declare if you call it like so: jsonToCsv($strJson,"/save/path/csvFile.csv");
  2. Line 116: if(isset($strTempFile) && file_exists($strTempFile)) {
    // Delete the temp file
    unlink($strTempFile);
    }

@MrZANO
Copy link

MrZANO commented Jun 13, 2018

Hello,
i have a problem

my json is
{ "response": [ { "pos": [ { "position": 1, "page": 1, "directory": "\/colorazione\/laffascinante-effetto-dei-capelli-biondo-scuro\/", "url": "https:\/\/www.example.it\/colorazione\/laffascinante-effetto-dei-capelli-biondo-scuro\/", "visibility": 3, "traffic": 80, "ad_budget": 35.2, "title": "L'affascinante effetto dei capelli biondo scuro", "kd": 33, "traffic_volume": 510, "cpc": 0.44, "delta_traffic": 0, "trend": { "trend": 0, "abs": 0, "per": 0 }, "tags": [ "color" ] }, { "position": 2, "page": 1, "directory": "\/colorazione\/biondo-scuro-castano-chiaro-bronde\/", "url": "https:\/\/www.example.it\/colorazione\/biondo-scuro-castano-chiaro-bronde\/", "visibility": 1, "traffic": 28, "ad_budget": 12.32, "title": "Biondo scuro, castano chiaro, bronde: quale scegliere?", "kd": 33, "traffic_volume": 510, "cpc": 0.44, "delta_traffic": 0, "trend": { "trend": 0, "abs": 0, "per": 0 }, "tags": [ "color" ] }, { "position": 3, "page": 1, "directory": "\/colorazione\/capelli-biondo-scuro-a-chi-stanno-bene\/", "url": "https:\/\/www.example.it\/colorazione\/capelli-biondo-scuro-a-chi-stanno-bene\/", "visibility": 1, "traffic": 20, "ad_budget": 8.8, "title": "Capelli biondo scuro a chi stanno bene? - Consigli Beauty example", "kd": 33, "traffic_volume": 510, "cpc": 0.44, "delta_traffic": 0, "trend": { "trend": 0, "abs": 0, "per": 0 }, "tags": [ "color" ] } ], "keyword": "biondo scuro", "tags": [ "color", "hair color" ], "delete_date": "0", "date": 20180608, "trend_date": 20180601 }, { "pos": [ { "position": 1, "page": 1, "directory": "", "url": "https:\/\/www.example.it\/colorazione", "visibility": 0, "traffic": 0, "ad_budget": 0, "title": "Trova la colorazione che fa per te - Tinte per capelli - example", "kd": 26, "traffic_volume": 20, "cpc": 0.4, "delta_traffic": 0, "trend": { "trend": 1, "abs": 3, "per": 75 }, "tags": [ "hair color" ] } ], "keyword": "tinte per capelli colori", "tags": [ "hair color", "product" ], "delete_date": "0", "date": 20180608, "trend_date": 20180601 }, { "pos": [ { "position": 1, "page": 1, "directory": "\/colorazione\/capelli-color-cioccolato-fai-da-te\/", "url": "https:\/\/www.example.it\/colorazione\/capelli-color-cioccolato-fai-da-te\/", "visibility": 0, "traffic": 8, "ad_budget": 3.28, "title": "Capelli color cioccolato: come farli comodamente a casa", "kd": 24, "traffic_volume": 56, "cpc": 0.41, "delta_traffic": 8, "trend": { "trend": 1, "abs": 1, "per": 50 }, "tags": [ "color" ] } ], "keyword": "tinta cioccolato", "tags": [ "color", "hair color" ], "delete_date": "0", "date": 20180608, "trend_date": 20180601 }, { "pos": [ { "position": 1, "page": 1, "directory": "\/pelle\/brufoli-mento-come-trattarli\/", "url": "https:\/\/www.example.it\/pelle\/brufoli-mento-come-trattarli\/", "visibility": 1, "traffic": 28, "ad_budget": 8.96, "title": "Brufoli sul mento: perch\u00e9 compaiono e come eliminarli", "kd": 45, "traffic_volume": 207, "cpc": 0.32, "delta_traffic": 0, "trend": { "trend": 0, "abs": 0, "per": 0 }, "tags": [ "imperfections" ] } ], "keyword": "brufoli sul mento", "tags": [ "imperfections", "skin care" ], "delete_date": "0", "date": 20180608, "trend_date": 20180601 }, { "pos": [ { "position": 1, "page": 1, "directory": "\/colorazione\/bellezza\/example\/nutrisse\/", "url": "https:\/\/www.example.it\/colorazione\/bellezza\/example\/nutrisse\/5-4-castano-chiaro-ramato", "visibility": 0, "traffic": 12, "ad_budget": 3.36, "title": "Castano Pralina Castano Chiaro Ramato (5.4) - Nutrisse - example", "kd": 42, "traffic_volume": 84, "cpc": 0.28, "delta_traffic": 0, "trend": { "trend": 0, "abs": 0, "per": 0 }, "tags": [ "color" ] } ], "keyword": "castano chiaro ramato", "tags": [ "color", "hair color" ], "delete_date": "0", "date": 20180608, "trend_date": 20180601 }, { "pos": [ { "position": 1, "page": 1, "directory": "\/colorazione\/capelli-color-cioccolato-fai-da-te\/", "url": "https:\/\/www.example.it\/colorazione\/capelli-color-cioccolato-fai-da-te\/", "visibility": 0, "traffic": 28, "ad_budget": 12.32, "title": "", "kd": 30, "traffic_volume": 177, "cpc": 0.44, "delta_traffic": 0, "trend": { "trend": 0, "abs": 0, "per": 0 }, "tags": [ "color" ] } ], "keyword": "capelli cioccolato", "tags": [ "color", "hair color" ], "delete_date": "0", "date": 20180608, "trend_date": 20180601 }, { "pos": [ { "position": 2, "page": 1, "directory": "\/colorazione\/bellezza\/example\/belle-color\/", "url": "https:\/\/www.example.it\/colorazione\/bellezza\/example\/belle-color\/24-castano-scuro", "visibility": 0, "traffic": 16, "ad_budget": 3.2, "title": "Castano Scuro (24) - Belle Color - example", "kd": 31, "traffic_volume": 288, "cpc": 0.2, "delta_traffic": 0, "trend": { "trend": 0, "abs": 0, "per": 0 }, "tags": [ "color" ] } ], "keyword": "castano scuro", "tags": [ "color", "hair color" ], "delete_date": "0", "date": 20180608, "trend_date": 20180601 }, { "pos": [ { "position": 2, "page": 1, "directory": "", "url": "https:\/\/www.example.it\/colorazione", "visibility": 1, "traffic": 8, "ad_budget": 3.6, "title": "Trova la colorazione che fa per te - Tinte per capelli - example", "kd": 31, "traffic_volume": 147, "cpc": 0.45, "delta_traffic": 0, "trend": { "trend": 0, "abs": 0, "per": 0 }, "tags": [ "hair color" ] } ], "keyword": "colori per capelli", "tags": [ "hair color", "product" ], "delete_date": "0", "date": 20180608, "trend_date": 20180601 }, { "pos": [ { "position": 2, "page": 1, "directory": "", "url": "https:\/\/www.example.it\/colorazione", "visibility": 1, "traffic": 24, "ad_budget": 11.76, "title": "Trova la colorazione che fa per te - Tinte per capelli - example", "kd": 34, "traffic_volume": 409, "cpc": 0.49, "delta_traffic": 12, "trend": { "trend": 1, "abs": 2, "per": 50 }, "tags": [ "hair color" ] } ], "keyword": "tinte capelli", "tags": [ "hair color", "product" ], "delete_date": "0", "date": 20180608, "trend_date": 20180601 }, { "pos": [ { "position": 2, "page": 1, "directory": "", "url": "https:\/\/www.example.it\/colorazione", "visibility": 3, "traffic": 16, "ad_budget": 7.2, "title": "Trova la colorazione che fa per te - Tinte per capelli - example", "kd": 29, "traffic_volume": 270, "cpc": 0.45, "delta_traffic": 0, "trend": { "trend": 0, "abs": 0, "per": 0 }, "tags": [ "hair color" ] } ], "keyword": "tinte per capelli", "tags": [ "hair color", "product" ], "delete_date": "0", "date": 20180608, "trend_date": 20180601 } ], "count": 350, "balance": 189350 }

i modified the scipt in line 56 and added
$json = $json['response'];

I got a csv done this way
pos,keyword,tags,delete_date,date,trend_date Array,"biondo scuro",Array,0,20180608,20180601 Array,"tinte per capelli colori",Array,0,20180608,20180601 Array,"tinta cioccolato",Array,0,20180608,20180601 Array,"brufoli sul mento",Array,0,20180608,20180601 Array,"castano chiaro ramato",Array,0,20180608,20180601 Array,"capelli cioccolato",Array,0,20180608,20180601 Array,"castano scuro",Array,0,20180608,20180601 Array,"colori per capelli",Array,0,20180608,20180601 Array,"tinte capelli",Array,0,20180608,20180601 Array,"tinte per capelli",Array,0,20180608,20180601
how can I tell the script that must also take the keys (and values) inside the matrix?

Thanks

@wint969
Copy link

wint969 commented May 23, 2019

awesome, big thanks!!!

@codeplayyy
Copy link

Awesome work!

@buildsomethingdifferent
Copy link

what if we have a spaces between the json value , it would effect the output of csv file.

@jakebathman
Copy link
Author

@buildsomethingdifferent what do you mean? Can you give some example JSON?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment