DEV Community

Robert Look
Robert Look

Posted on

How To Convert CSV To JSON Using PHP?

This is a simple and short tutorial on How to CSV to JSON in PHP. we have to make features like fetch data from CSV file and insert that CSV file data into the Mysql database. we have to need to convert how to convert CSV to JSON. The main purpose of this tutorial is to learn how to convert CSV to JSON.

How To Convert CSV to JSON using PHP? ( Easy Way ) -Step by Step

<?php

$error = '';

if(isset($_POST["upload_file"]))
{
  if($_FILES['file']['name'])
  {
    $file_array = explode(".", $_FILES['file']['name']);

    $file_name = $file_array[0];

    $extension = end($file_array);

    if($extension == 'csv')
    {
      $column_name = array();

      $final_data = array();

      $file_data = file_get_contents($_FILES['file']['tmp_name']);

      $data_array = array_map("str_getcsv", explode("\n", $file_data));

      $labels = array_shift($data_array);

      foreach($labels as $label)
      {
        $column_name[] = $label;
      }

      $count = count($data_array) - 1;

      for($j = 0; $j < $count; $j++)
      {
        $data = array_combine($column_name, $data_array[$j]);

        $final_data[$j] = $data;
      }

      header('Content-disposition: attachment; filename='.$file_name.'.json');

      header('Content-type: application/json');

      echo json_encode($final_data);

      exit;
    }
    else
    {
      $error = 'Only <b>.csv</b> file allowed';
    }
  }
  else
  {
    $error = 'Please Select CSV File';
  }
}

?>
Enter fullscreen mode Exit fullscreen mode

Top comments (0)