Convert CSV To JSON Using PHP (With Header Row As Keys)

yotube
0

Hi! Here is the php script to convert csv to json with header row as keys. Both csv and json are used to store data but json is little more verbose and human readable and has become popular data exchange format among modern web services. Converting csv data into json format is little tricky especially if you want your json to be properly formatted as key:value pairs. The csv header row should be used as keys and the subsequent rows as values to form json string.

Unfortunately there is no direct way to do this but likely there is a workaround to bring out the desired result. The method used here is by far the most effective solution to convert csv to json with header row as keys.

Converting CSV to JSON using PHP

Let's take a sample csv file with header and some rows and convert it to json using php script.

Data.csv


Id,Name,Position,Salary
1,Suki Burks,Developer,$114500
2,Fred Zupers,Technical Author,$145000
3,Gavin Cortez,Team Leader,$235500

PHP Function to Convert CSV to JSON

This is the php function to convert csv to json representation. The function takes up a csv file as parameter, stores the headers as a separate key array and read the subsequent rows one by one into an array and finally combine both key and data array to form a proper key-value pair representation.


<?php
// php function to convert csv to json format
function csvToJson($fname) {
// open csv file
if (!($fp = fopen($fname, 'r'))) {
die("Can't open file...");
}

//read csv headers
$key = fgetcsv($fp,"1024",",");

// parse csv rows into array
$json = array();
while ($row = fgetcsv($fp,"1024",",")) {
$json[] = array_combine($key, $row);
}

// release file handle
fclose($fp);

// encode array to json
return json_encode($json);
}
?>
  • The function fgetcsv($fp,"1024",",") reads a row from the csv file into an array. The second parameter "1024" is the maximum character length of the csv row and the third parameter "," represents the column delimiter.
  • The function json_encode() encodes the php array into json string.

Function Usage

Call the above php function like this to convert csv to json.


<?php
print_r(csvToJson("data.csv"));

// output

// [{"Id":"1","Name":"Suki Burks","Position":"Developer","Salary":"$114500"},{"Id":"2","Name":"Fred Zupers","Position":"Technical Author","Salary":"$145000"},{"Id":"3","Name":"Gavin Cortez","Position":"Team Leader","Salary":"$235500"}]
?>

If you want json to be stored in a separate file, then open a file and write to it. Check this tutorial to know how to write to a json file.

Thus with this small php utility function you can very easily convert csv to json string.

Also Read: How to Import CSV to MySQL Database in PHP

Post a Comment

0Comments
Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Learn More
Accept !
To Top