How to convert CSV to JSON in PHP

In this example I am going to show you how to convert CSV to JSON using PHP programming language. CSV stands for comma separated values and JSON stands for JavaScript Object Notation. These are actually data formats used for representations.

Having data formats in CSV and JSON are advantageous because of their light-weight, easy to representation and easy to parse. JSON format is currently widely used in REST response.

In this example I am going to show both examples on how to convert CSV file and CSV string to JSON string and JSON file. I am also going to show you how to pretty print the output JSON format.

Prerequisites

PHP 7.4.3, Apache 2.4 HTTP Server

Project Directory

It’s assumed that you have setup Apache and PHP.

Now we will create a project root directory called php-csv-json under the Apache server’s htdocs folder.

I may not mention the project root directory in subsequent sections and I will assume that we are talking with respect to the project root directory.

CSV String to JSON String

The first example I am going to show you how to convert CSV string to JSON string.

<?php

header('Content-type: application/json; charset=UTF-8');

$csv = 'student_id,student_dob,student_email,student_address
1,01-01-1980,sumit@email.com,Garifa
2,01-01-1982,gourab@email.com,Garia
3,01-01-1982,debina@email.com,Salt Lake
4,01-01-1992,souvik@email.com,Alipore
5,01-01-1990,liton@email.com,Salt Lake';
$content = array_map("str_getcsv", explode("\n", $csv));

$headers = $content[0];

$json = [];

foreach ($content as $row_index => $row_data) {
	if($row_index === 0) continue;

	foreach ($row_data as $col_idx => $col_val) {
		$label = $headers[$col_idx];
		$json[$row_index][$label] = $col_val;
	}
}

//output as JSON string
echo json_encode($json, JSON_PRETTY_PRINT);

In the above PHP code I have declared the content type in HTTP header for displaying as JSON output or writing as JSON output.

Next I have put the CSV string into a variable. Then I have read the CSV content into an array using the function str_getcsv.

The first row contains header fields in the CSV data, so I extracted using the index 0.

Next I iterate through each index from the array except the header one. Then for each row I am iterating through column values and putting into an array to build the JSON string which will be displayed later using json_encode() function.

The json_encode() function by default prints the JSON in one line so I have passed JSON_PRETTY_PRINT as a second parameter for pretty printing.

The output in JSON string you will see on the browser when you hit the URL http://localhost/php-csv-json/php-csv-json.php.

php csv to json

CSV File to JSON File

The conversion logic from CSV to JSON is exactly same as above but only the reading and writing parts are different. Even you can read CSV string and write to JSON file or read CSV file and write to a JSON string.

<?php

header('Content-type: application/json; charset=UTF-8');

$file = "student.csv";
$csv = file_get_contents($file);

$content = array_map("str_getcsv", explode("\n", $csv));

$headers = $content[0];

$json = [];

foreach ($content as $row_index => $row_data) {
	if($row_index === 0) continue;

	foreach ($row_data as $col_idx => $col_val) {
		$label = $headers[$col_idx];
		$json[$row_index][$label] = $col_val;
	}
}

//write to JSON file
$fp = fopen('student.json', 'w');
fwrite($fp, json_encode($json, JSON_PRETTY_PRINT));
fclose($fp);

The file I am reading is kept under the same folder where I have put this PHP file. The output JSON file is also generated under the same folder. You will get the same output in the JSON file.

Source Code

Download

Leave a Reply

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