Friday 16 October 2020

How to Convert CSV to JSON in PHP

This is simple and short tutorial on How do we convert CSV file data into JSON format in PHP. In this world of web programming, sometimes we have to make feature like fetch data from CSV file and insert that CSV file data into Mysql database then at that time we have need to convert CSV to JSON. The main purpose of this tutorial is to learn how can we easy way to convert CSV data or file to JSON object using PHP script.

Advantages of CSV

  1. CSV files can be opened or edited by text editors like notepad.
  2. In data-warehouse, CSV follows a reasonably flat, simple schema.
  3. Any programing language to parse CSV data is trivial, generating it's extremely easy.
  4. CSV is safe and may clearly differentiate between the numeric values and text. CSV doesn't manipulate data and stores it as-is.
  5. In CSV, you write column headers just one occasion where as in Excel, you've got to possess a start tag and end tag for every column in each row.
  6. Importing CSV files are often much faster, and it also consumes less memory.
  7. It's easy to programmatically manipulate CSV since, after all, they're simple text files.
  8. CSV are often opened with any text editor in Windows like notepad, MS Excel, Microsoft Works 9, etc.

Advantages of JSON

  1. JSON is a portable that means it can be parse and write are available in many programming languages like JavaScript.
  2. By using JSON we can online transfer large data from source to destination in the form of array or objects.
  3. IN JSON we can transfer data in plain text or unformatted data like comma speratted or delimited data.
  4. JSON is better that XML, this is because it has more sufficient space than XML data structure.
  5. JSON has no tag name and it has structure which is nested braces instead of verbose tags.
  6. In exchange of data JSON is faster than XML.

So here we have seen benefits of CSV and JSON data and both are mainly used for data exchange. But if you have work on any web services than JSON data is mostly used for transmit or exchange of data on the web. So if you have data in CSV file and you have to exchange that data then you must convert that data into JSON format and you can easily exchange data online.

In PHP language there many functions are available for parse or read data from CSV file and then convert that data into PHP array and lastly for convert data into JSON then we can use json_encode() function.

Sample Input CSV Data

Company Name,Address,City,State,ZIP/PIN CODE,Country,Website,Industry,First Name,Last Name,Phone Number,Designation,Email
Cougar Investment,3570 Thunder Road,Mountain View,CA,94041,USA,,Animal care and service worker,Devin,Taylor,650-564-1816,Animal care and service worker,
Robert Hall,1729 Lyndon Street,Slatington,PA,18080,USA,,Media,Ruby,Gibson,610-767-5251,News anchor,



$error = '';

    $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);

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


<!DOCTYPE html>
    	<title>Convert CSV to JSON using PHP</title>
    	<meta name="viewport" content="width=device-width, initial-scale=1.0">
      <script src=""></script>
    	<link rel="stylesheet" href="">
  		<div class="container">
  			<br />
  			<br />
    		<h1 align="center">Convert CSV to JSON using PHP</h1>
    		<br />
    		<div class="panel panel-default">
          <div class="panel-heading">
            <h3 class="panel-title">Select CSV File</h3>
          <div class="panel-body">
            if($error != '')
              echo '<div class="alert alert-danger">'.$error.'</div>';
            <form method="post" enctype="multipart/form-data">
              <div class="col-md-6" align="right">Select File</div>
              <div class="col-md-6">
                <input type="file" name="file" />
              <br /><br /><br />
              <div class="col-md-12" align="center">
                <input type="submit" name="upload_file" class="btn btn-primary" value="Upload" />

Output JSON Data

    "Company Name": "Cougar Investment",
    "Address": "3570 Thunder Road",
    "City": "Mountain View",
    "State": "CA",
    "ZIP/PIN CODE": "94041",
    "Country": "USA",
    "Website": "",
    "Industry": "Animal care and service worker",
    "First Name": "Devin",
    "Last Name": "Taylor",
    "Phone Number": "650-564-1816",
    "Designation": "Animal care and service worker",
    "Email": ""
    "Company Name": "Robert Hall",
    "Address": "1729 Lyndon Street",
    "City": "Slatington",
    "State": "PA",
    "ZIP/PIN CODE": "18080",
    "Country": "USA",
    "Website": "",
    "Industry": "Media",
    "First Name": "Ruby",
    "Last Name": "Gibson",
    "Phone Number": "610-767-5251",
    "Designation": "News anchor",
    "Email": ""

1 comment: