Last active
April 11, 2017 10:07
-
-
Save lomboboo/d9703f7fdac73100f566175da99a5635 to your computer and use it in GitHub Desktop.
Converts json to csv. If json is multidimensional - serializing it
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
<?php | |
/* | |
Plugin Name: json2csv | |
Description: Converts json to csv. If json is multidimensional - serializing it | |
Usage: Example is below code | |
Version: 0.1 | |
Author: Lomboboo | |
*/ | |
class JSON2CSV { | |
private $jsonFilename; | |
private $csv; | |
function __construct($jsonFilename, $csvName = null) | |
{ | |
$this->jsonFilename = $jsonFilename; | |
$this->csv = fopen($csvName ? $csvName.'.csv' : $jsonFilename.'.csv', 'w') or die("Unable to open file!"); | |
} | |
public function convert() { | |
$json = file_get_contents($this->jsonFilename . '.json'); | |
$array = json_decode($json, true); | |
$keys = array(); | |
// collect keys | |
foreach($array as $line){ | |
foreach($line as $key => $value){ | |
if(!in_array($key, $keys)) | |
$keys[] = $key; | |
} | |
} | |
$keyString = implode(",", $keys); | |
fwrite($this->csv, "$keyString\n"); // writing header to csv | |
foreach ($array as $line) | |
{ | |
$outputArray = array(); | |
foreach($keys as $key){ | |
if(array_key_exists($key, $line)){ | |
if ( is_array($line[$key]) ) { // if key value is array - serialize it | |
$s = serialize($line[$key]); | |
$outputArray[] = str_replace(',', '', $s); | |
} else { | |
$outputArray[] = str_replace(',', '', str_replace("\r\n",'', $line[$key])); | |
} | |
} else { | |
$outputArray[] = ""; | |
} | |
} | |
$outputString = implode(",", $outputArray); | |
fwrite($this->csv, "$outputString\n"); | |
} | |
fclose($this->csv); | |
} | |
} | |
// example | |
$json1 = new JSON2CSV('file', 'csv'); // second parameter is csv output name | optional | default is json name | |
$json1->convert(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment