Convert CSV to JSON PHP – PHP Tutorial

Convert CSV file to JSON in PHP. In this tutorial, we will learn how to convert CSV data or file into a JSON object in PHP.

You should also read following PHP JSON post:

CSV (Comma Separated Values) and JSON (JavaScript Object Notation) are two commonly used data formats. CSV is used for storing data in a tabular format where each row represents a record, and each column represents a field. JSON, on the other hand, is a lightweight data interchange format that is used to represent data as a collection of key-value pairs.

How to convert CSV to JSON in PHP

Sometimes it may be necessary to convert data from CSV format to JSON format. In this article, we will discuss how to convert CSV to JSON using PHP.

Let’s talk about CSV to array and JSON:

We have one CSV file and it’s URL https://docs.google.com/spreadsheets/d/e/2PACX-1vTEKCTdbMgSEt7UCymQ956PIYsHei51gpCtPou4VGugKRztJVuZSNuDXKDrdDiZxx6-Ebepte8P6OlG/pub?output=csv. It contains the name, age, email id.

This file looks like below:

PHP script to convert CSV file to JSON

Use the following steps to convert CSV file to JSON object in PHP:

Step 1. First of all, we will read the CSV file from the given path and convert CSV to array in PHP.

Step 2. When we have converted the CSV file into an array. After that, we will convert the array to JSON in PHP.

<?php

/*
 * Converts CSV File to JSON PHP Script
 * Example uses Google Spreadsheet CSV
*/

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

//Set your file path here
$filePath = 'https://docs.google.com/spreadsheets/d/e/2PACX-1vTEKCTdbMgSEt7UCymQ956PIYsHei51gpCtPou4VGugKRztJVuZSNuDXKDrdDiZxx6-Ebepte8P6OlG/pub?output=csv';

// define two arrays for storing values
$keys = array();
$newArray = array();

//PHP Function to convert CSV into array
function convertCsvToArray($file, $delimiter) { 
  if (($handle = fopen($file, 'r')) !== FALSE) { 
    $i = 0; 
    while (($lineArray = fgetcsv($handle, 4000, $delimiter, '"')) !== FALSE) { 
      for ($j = 0; $j < count($lineArray); $j++) { 
        $arr[$i][$j] = $lineArray[$j]; 
      } 
      $i++; 
    } 
    fclose($handle); 
  } 
  return $arr; 
} 
// Call the function convert csv To Array
$data = convertCsvToArray($filePath, ',');

// Set number of elements (minus 1 because we shift off the first row)
$count = count($data) - 1;
  
//First row for label or name
$labels = array_shift($data);  
foreach ($labels as $label) {
  $keys[] = $label;
}

// assign keys value to ids, we add new parameter id here
$keys[] = 'id';
for ($i = 0; $i < $count; $i++) {
  $data[$i][] = $i;
}
  
// combine both array
for ($j = 0; $j < $count; $j++) {
  $d = array_combine($keys, $data[$j]);
  $newArray[$j] = $d;
}

// convert array to json php using the json_encode()
$arrayToJson = json_encode($newArray);

// print converted csv value to json
echo $arrayToJson;
?>

Explanation:

  1. We first open the CSV file using the fopen() function with the mode set to 'r' (read).
  2. We read the first row of the CSV file as the header using the fgetcsv() function.
  3. We initialize an empty array to hold the data.
  4. We loop through the remaining rows of the CSV file using a while loop and add each row to the data array using the array_combine() function to combine the header row with the current row.
  5. We close the CSV file using the fclose() function.
  6. We convert the data array to JSON using the json_encode() function.
  7. We output the JSON using the echo statement.

Conclusion

In this article, we have discussed how to convert CSV to JSON using PHP. We first read the CSV file using the fopen() function, and then we converted the data to JSON format using the json_encode() function. Finally, we saved the JSON data to a file using the file_put_contents() function. By following these steps, we can easily convert data from CSV format to JSON format using PHP.

Recommended PHP Tutorials

  1. Autocomplete Search Box in PHP MySQL
  2. Compare Arrays PHP | PHP array_diff() Function
  3. Get, Write, Read, Load, JSON File from Url PHP
  4. Functions: Remove First Character From String PHP
  5. Remove Specific/Special Characters From String In PHP
  6. How to Replace First and Last Character From String PHP
  7. Reverse String in PHP
  8. Array Push, POP PHP | PHP Array Tutorial
  9. PHP Search Multidimensional Array By key, value and return key
  10. json_encode()- Convert Array To JSON | Object To JSON PHP
  11. PHP remove duplicates from multidimensional array
  12. PHP Remove Duplicate Elements or Values from Array PHP
  13. Get Highest Value in Multidimensional Array PHP
  14. PHP Get Min or Minimum Value in Array
  15. String PHP to Uppercase, Lowercase & First Letter Uppercase
  16. PHP: isset() vs empty() vs is_null()
  17. Chunk_split PHP Function Example
  18. PHP Function: Date and Time With Examples
  19. Reverse Number in PHP | PHP Tutorial

AuthorAdmin

My name is Devendra Dode. I am a full-stack developer, entrepreneur, and owner of Tutsmake.com. I like writing tutorials and tips that can help other developers. I share tutorials of PHP, Python, Javascript, JQuery, Laravel, Livewire, Codeigniter, Node JS, Express JS, Vue JS, Angular JS, React Js, MySQL, MongoDB, REST APIs, Windows, Xampp, Linux, Ubuntu, Amazon AWS, Composer, SEO, WordPress, SSL and Bootstrap from a starting stage. As well as demo example.

Leave a Reply

Your email address will not be published. Required fields are marked *