Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
60 changes: 60 additions & 0 deletions arrayToCSV.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
<?php


function arrayToCSV($fields = array(), $delimiter = ',', $enclosure = '"'){
$str = '';
$escape_char = '\\';
$children = array();
foreach ($fields as $value) {

if(gettype($value) == 'array'){
$children[] = $value;
continue;
}

if (strpos($value, $delimiter) !== false ||
strpos($value, $enclosure) !== false ||
strpos($value, "\n") !== false ||
strpos($value, "\r") !== false ||
strpos($value, "\t") !== false ||
strpos($value, ' ') !== false) {
$str2 = $enclosure;
$escaped = 0;
$len = strlen($value);
for ($i=0;$i<$len;$i++) {



if ($value[$i] == $escape_char) {
$escaped = 1;
} else if (!$escaped && $value[$i] == $enclosure) {
$str2 .= $enclosure;
} else {
$escaped = 0;
}
$str2 .= $value[$i];
}
$str2 .= $enclosure;
$str .= $str2.$delimiter;
} else {
if(count($value)==0){

$str .="novalue".$delimiter;
}else{
$str .= $value.$delimiter;
}
}
}

foreach ($children as $value) {

$str .=arrayToCSV($value);
}


// $str = substr($str,0,-1);

return $str;
}

?>
2 changes: 2 additions & 0 deletions index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
<html><head><title>JSON 2 CSV </title></head>
<body> <a href="json2csv.php"> Click here to convert your json to csv</a> </body> </html>
94 changes: 74 additions & 20 deletions json2csv.class.php
Original file line number Diff line number Diff line change
@@ -1,5 +1,10 @@
<?php

require_once('arrayToCSV.php');

ini_set('memory_limit', '-1');


class JSON2CSVutil{

public $dataArray;
Expand All @@ -11,48 +16,97 @@ function readJSON($JSONdata){
return $this->dataArray;
}

function JSONfromFile($file){
$this->dataArray = json_decode(file_get_contents($file),1);
$this->prependColumnNames();
return $this->dataArray;
function isNested($array){
foreach($array as $data){
if(is_array($data)){
return TRUE;
}
}
return FALSE;
}


function getAllKeys($array){
$result = array();
$children = array();
foreach($array as $sub=>$value) {
if(gettype($value)=='array'){
$children[] = $value;
//$result = array_merge($result,$this->getAllKeys($value));
}else{
$result [] = $sub;
}
}

foreach ($children as $key => $value) {
$result = array_merge($result,$this->getAllKeys($value));
}
return $result;
}

private function prependColumnNames(){
foreach(array_keys($this->dataArray[0]) as $key){
$keys[0][$key] = $key;
function prependColumnNames(){
$keys = array();
foreach ($this->dataArray as $key => $value) {

if($this->isNested($value)){
$keys[] = $this->getAllKeys($this->dataArray[$key]);
break;
}
}

if(count($keys)==0){
$keys[] = $this->getAllKeys($this->dataArray[0]);
}

$this->dataArray = array_merge($keys, $this->dataArray);
}

function save2CSV($file){
function browserDL($CSVname){

if($this->isItNested() || !is_array($this->dataArray)){
echo "JSON is either invalid or has nested elements.";
echo "<h1>JSON is either invalid or you encountered an edge case I missed. Please let me know at [email protected]<h1>";
}
else{
$fileIO = fopen($file, 'w+');
header("Content-Type: text/csv; charset=utf-8");
header("Content-Disposition: attachment; filename=$CSVname");

$output = fopen('php://output', 'w');

foreach ($this->dataArray as $fields) {
fputcsv($fileIO, $fields);
fwrite($output,arrayToCSV($fields)."\n");
}
fclose($fileIO);
}
}
function browserDL($CSVname){


function JSONfromFile($file){


$this->dataArray = json_decode(file_get_contents($file),TRUE);
$this->prependColumnNames();
return $this->dataArray;
}


function save2CSV($file){

if($this->isItNested() || !is_array($this->dataArray)){
echo "<h1>JSON is either invalid or has nested elements.</h1>";
echo "<h1>JSON is either invalid or you encountered an edge case I missed. Please let me know at [email protected]<h1>";
}
else{
header("Content-Type: text/csv; charset=utf-8");
header("Content-Disposition: attachment; filename=$CSVname");

$output = fopen('php://output', 'w');
echo 'orey '.$file;
ob_flush();

$fileIO = fopen($file, 'w+');
foreach ($this->dataArray as $fields) {
fputcsv($output, $fields);
fputcsv($fileIO, $fields);
}
fclose($fileIO);
}
}

private function isItNested(){
function isItNested(){
foreach($this->dataArray as $data){
if(is_array($data)){
$isNested = TRUE;
Expand Down
13 changes: 9 additions & 4 deletions json2csv.php
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
<?php

ini_set('memory_limit', '-1');

if((isset($_FILES["file"]["type"]) && $_FILES["file"]["type"] != NULL)
|| (isset($_POST['json']) && $_POST['json'] != NULL)
|| (isset($argv[1]))){
Expand All @@ -19,15 +21,18 @@
$filepath = "JSON2.CSV";
}


$JSON2CSV->savejsonFile2csv($arguments["file"], $filepath);
}
elseif($_FILES["file"]["type"] != NULL){
elseif(($_FILES["file"]["type"]) != NULL){

$JSON2CSV->JSONfromFile($_FILES["file"]["tmp_name"]);
$JSON2CSV->browserDL("JSON2.CSV");
$JSON2CSV->browserDL(str_replace("json", "csv", $_FILES["file"]["name"]));
}
elseif($_POST['json'] != NULL){

$JSON2CSV->readJSON($_POST['json']);
$JSON2CSV->browserDL("JSON2.CSV");
$JSON2CSV->browserDL("JSON.CSV");
}
}
else{
Expand All @@ -38,7 +43,7 @@

<form action="<?php echo $_SERVER['SCRIPT_NAME']; ?>" method="post" enctype="multipart/form-data">
<label for="json">JSON data:</label>
<textarea name="json" cols="150" rows="40">
<textarea name="json" cols="70" rows="20">

</textarea>
<br />
Expand Down
Loading