JSON to CSV Converter using PHP - Source Code

If you want to convert simple json data format to csv file, you can see that we have created a function.

How does this function work?

  • Using file_get_contents(FILE_NAME) you can read all contents for JSON file.
  • Using json_decode($json, true) you can convert json string to array.
  • Using array_keys($row) you can get header keys.
  • Using fputcsv($fp, $header) you can add values into CSV file row by row.

Note

Only following JSON format is allowed when converting JSON to CSV.


[
    {
        "key1": "value 1",
        "key 2": "value 2",
        "key 3": "value 4"
    }
]

FULL SOURCE CODE:

html code:

Get input box with file type. when user select file then check file selected or not. How to check this? Add onchange event on input box and add checkfile() function. After that add one button with name converter. using that button we can send selected file to php for convert json data to csv format. Add click event on that button. When user click on that function call getJSON() function.


<!doctype html>
<html lang="en">
    
    <body>
        <div class="container-fluid main">
            <div class="row main-row">
                <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
                    <div class="card border-0 shadow">
                        <div class="card-body p-3">
                            <div class="card-text">
                                <h1>JSON to CSV Converter</h1>
                                <div class="row">
                                    <div class="col-lg-6 col-md-6 col-sm-12 col-xs-12">
                                        <div class="form-group">
                                            <label>Enter JSON Data:</label>
                                            <textarea id="jsondata" class="form-control" name="xmldata" rows="5" required></textarea>
                                        </div>
                                    </div>
                                    <div class="col-lg-6 col-md-6 col-sm-12 col-xs-12">
                                        <div class="form-group">
                                            <label>Upload File:</label>
                                            <form>
                                                <input id="jsonfile" type="file" onchange="checkfile()">
                                                <p id="drag_name">Drag your files here</p>
                                            </form>
                                        </div>
                                    </div>
                                </div>
                                <button class="btn btn-primary" type="submit" onclick="getCSV()">CONVERT</button>
                                <div class="form-group">
                                    <label>Result:</label>
                                    <div id="result" class="prettyprint" style="min-height: 40vh;"></div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </body>
</html>
JavaScript Code:
  • Get JSON data file and check file is selected or not.
  • Check file size is greater than 2 MB or not. If file size is greater than 2MB then sometimes there is an error while converting the file, so a 2MB size lock is placed.
  • Using AJAX send file on PHP page. In response we get converting status, downloading link.
Success Response:

{"status":"success","download":"https:\/\/easyconvertertools.com\/code\/files\/data.csv","data":"key1,\"key 2\",\"key 3\"\n\"value 1\",\"value 2\",\"value 4\"\n"}


<script>
    let filename = "";
    function getCSV() {
        let str = document.getElementById('jsondata').value;
        if (str !== "") {
            var data = new FormData();
        	data.append('data', str);
        	
            var xmlhttp = new XMLHttpRequest();
            xmlhttp.onreadystatechange = function() {
              if (this.readyState == 4 && this.status == 200) {
                let data = JSON.parse(this.responseText);
                document.getElementById('result').innerText = data["data"];
                filename = data["download"];
                document.getElementById('jsondata').value = "";
              }
            };
            xmlhttp.open("POST", "jsontocsv.php?action=textdata", true);
            xmlhttp.send(data);
        } else {
            if(document.querySelector('#jsonfile').files.length == 0) {
        		alert('Error : No file selected');
        		return;
        	}
        	var file = document.querySelector('#jsonfile').files[0];
        	
        	if(file.size > 2*1024*1024) {
        		alert('Error : Exceeded size 2MB');
        		return;
        	}
        	
        	var data = new FormData();
        	data.append('file', document.querySelector('#jsonfile').files[0]);
        	var request = new XMLHttpRequest();
            request.open('post', 'jsontocsv.php?action=filedata');
            request.addEventListener('load', function(e) {
                let data = JSON.parse(this.responseText);
                document.getElementById('result').innerText = data["data"];
                filename = data["download"];
                
                document.getElementById('drag_name').innerText = "Drag your files here";
            });
            request.send(data);
        }
    }
    
    function checkfile() {
        if(document.querySelector('#jsonfile').files.length == 0) {
        		document.getElementById('drag_name').innerText = "Drag your files here";
        	} else {
        	    document.getElementById('drag_name').innerText = "1 file has selected";
        	}
    }
</script>
CSV to JSON Converter PHP function:

function jsonToCSV($jfilename, $cfilename)
{
    if (($json = file_get_contents($jfilename)) == false)
        die('Error reading json file...');
    $data = json_decode($json, true);
    $fp = fopen($cfilename, 'w');
    $header = false;
    foreach ($data as $row)
    {
        if (empty($header))
        {
            $header = array_keys($row);
            fputcsv($fp, $header);
            $header = array_flip($header);
        }
        fputcsv($fp, array_merge($header, $row));
    }
    fclose($fp);
    return;
}
jsontocsv.php

<?php
    $json_filename = 'files/data.json';
    $csv_filename = 'files/data.csv';

    if ($_GET["action"] == "filedata" && isset($_FILE["file"])) {
        $file = "files/".basename($_FILES["file"]["name"]);
        move_uploaded_file($_FILES["file"]["tmp_name"], $file);
        jsonToCSV($file, $csv_filename);
        
        $string = file_get_contents($csv_filename);
        
        $output = Array();
        $output["status"] = "success";
        $output["download"] = "https://easyconvertertools.com/code/".$csv_filename;
        $output["data"] = $string;
        echo json_encode($output);
        
    } else if ($_GET["action"] == "textdata") {
        $file="files/data.json";
        $myfile = fopen($file, "w") or die("Unable to open file!");
        fwrite($myfile, $_POST['data']);
        fclose($myfile);
        
        jsonToCSV($file, $csv_filename);
        $string = file_get_contents($csv_filename);
        
        $output = Array();
        $output["status"] = "success";
        $output["download"] = "https://easyconvertertools.com/code/".$csv_filename;
        $output["data"] = $string;
        echo json_encode($output);
    }
?>