Convert CSV to JSON PHP – PHP Tutorial
Php 20-Aug-2021

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.

Convert CSV to JSON PHP

This tutorial has a purpose to shows you 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

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

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;
?>