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.

We should also read this PHP JSON posts:

How to convert CSV to JSON in PHP

This tutorial has the purpose to shows us an easy way to convert CSV data or file to JSON object in 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;
?>

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
Jaspreet Singh Ghuman

Jaspreet Singh Ghuman

Jassweb.com/

Passionate Professional Blogger, Freelancer, WordPress Enthusiast, Digital Marketer, Web Developer, Server Operator, Networking Expert. Empowering online presence with diverse skills.

jassweb logo

Jassweb always keeps its services up-to-date with the latest trends in the market, providing its customers all over the world with high-end and easily extensible internet, intranet, and extranet products.

Contact
San Vito Al Tagliamento 33078
Pordenone Italy
Item added to cart.
0 items - 0.00
Open chat
Scan the code
Hello 👋
Can we help you?