CSV to JSON Converter using PHP

What are CSV files?

CSV stands for "comma-separated values". CSV data fields are separated by comma. The CSV file is used to store a spreadsheet or database.

What is JSON file Format?

JSON stands for JavaScript Object Notation. JSON file format is very easy to understand. Therefore it is used much more. The JSON file format is most commonly used in popular languages such as Java, php.

output

How to convert csv to json converter with PHP script using the following steps:

step 1: Get CSV file data in veriable.

    $input = "test1, test2, test3\ntemp1, temp2, temp3";
    

step 2: create a new blank file. & store data into that file.

    $file="files/csv.txt";
    $myfile = fopen($file, "w") or die("Unable to open file!");
    fwrite($myfile, $input);
    fclose($myfile);
    

step 3: Copy, paste following function into your code:

    function csvtojson($file) {
        if (($handle = fopen($file, "r")) !== FALSE) {
            $csvs = [];
            while(! feof($handle)) {
               $csvs[] = fgetcsv($handle);
            }
            $datas = [];
            $column_names = [];
            foreach ($csvs[0] as $single_csv) {
                $column_names[] = $single_csv;
            }
            foreach ($csvs as $key => $csv) {
                if ($key === 0) {
                    continue;
                }
                foreach ($column_names as $column_key => $column_name) {
                    $datas[$key-1][$column_name] = $csv[$column_key];
                }
            }
            $json = json_encode($datas);
            fclose($handle);
            return $json;
        }
    }
    

step 4: call csvtojson function with filename as a parameter.

    $data = csvtojson($file);
    

step 5: Your JSON format is ready.

    print_r($data);
    

Note: If you want to upload file and convert it into JSON format then Step 1 & 2 will be like the following code:

    $file = "files/".basename($_FILES["csvfile"]["name"]);
    move_uploaded_file($_FILES["csvfile"]["tmp_name"], $file);