How to Convert CSV to JSON in PHP?

03-Apr-2023

.

Admin

How to Convert CSV to JSON in PHP?

Hi Dev,

This tutorial is focused on how to convert CSV to JSON in PHP. you'll learn to convert CSV to JSON in PHP. We will use convert CSV to JSON using PHP. if you have a question about how to convert CSV to JSON using PHP then I will give a simple example with a solution.

Now, let's see the article on how to convert CSV to JSON using PHP. it's a simple example of how to convert CSV to JSON in PHP. you can understand the concept of a convert CSV to JSON in PHP. if you have a question about converting CSV to JSON using PHP then I will give a simple example with a solution.

Step 1: PHP script to convert CSV file to JSON


<?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 an 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 the 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 arrays

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;

?>

I hope it could help you...

#PHP