Convert PHP CSV to JSON

by Vincy. Last modified on February 24th, 2024.

JSON format is a widely used format while working with API development. Most of the existing API responses are in JSON format.

Converting CSV content into a JSON format is simple in PHP. In this article, we will see different methods of achieving this conversion.
View demo

Quick example

$csvFileContent= file_get_contents("animals.csv");
// Converts the CSV file content into line array 
$csvLineArray = explode("\n", $csvFileContent);
// Forms row results in an array format
$result = array_map("str_getcsv", $csvLineArray);
$jsonObject = json_encode($result);

The above quick example in PHP converts the CSV file content into JSON with few lines of code.

  1. First, it reads the .csv file content using the PHP file_get_contents() function.
  2. It explodes the CSV row by the (\n) escape sequence.
  3. Then, it iterates the line array and reads the line data of the CSV row.
  4. Finally, the resultant CSV row array is converted to JSON using the json_encode() function.

In step 3, the iteration happens with a single line of code. This line maps the array to callĀ  PHP str_getcsv to parse and convert the CSV lines into an array.

When we saw the methods of reading a CSV file, we created an example using str_getcsv function.

The below input file is saved and used for this PHP example.

Input CSV

1,Lion,Wild,"Lazy Boss"

Output JSON

This PHP quick example displays the below JSON output on the browser.

[["Id","Name","Type","Role"],["1","Lion","Wild","Lazy Boss"],["2","Tiger","Wild","CEO"],["3","Jaguar","Wild","Developer"]]

In the following sections, we will see two more examples of converting CSV files into JSON.

  1. Method 2: Convert CSV (containing header) into a JSON (associating the column=>value pair)
  2. Method 3: Upload a CSV file and convert it into JSON

upload and convert csv to json

Method 2: Convert CSV (containing header) into a JSON (associating the column=>value pair)

This example uses a CSV string as its input instead of a file.

It creates the header column array by getting the first row of the CSV file.

Then, the code iterates the CSV rows from the second row onwards. On each iteration, it associates the header column and the iterated data column.

This loop prepares an associative array containing the CSV data.

In the final step, the json_encode() function converts the associative array and writes it into an output JSON file.

$csvString = "Id,Name,Type,Role

$lineContent = array_map("str_getcsv", explode("\n", $csvString));

$headers = $lineContent[0];
$jsonArray = array();
$rowCount = count($lineContent);
for ($i=1;$i<$rowCount;$i++) {
    foreach ($lineContent[$i] as $key => $column) {
        $jsonArray[$i][$headers[$key]] = $column;

header('Content-type: application/json; charset=UTF-8');
$fp = fopen('animals.json', 'w');
fwrite($fp, json_encode($jsonArray, JSON_PRETTY_PRINT));

Output – The animal.json file

This is the output written to the animal.json file via this PHP program.

    "1": {
        "Id": "1",
        "Name": "Lion",
        "Type": "Wild",
        "Role": "Boss"
    "2": {
        "Id": "2",
        "Name": "Tiger",
        "Type": "Wild",
        "Role": "CEO"
    "3": {
        "Id": "3",
        "Name": "Jaguar",
        "Type": "Wild",
        "Role": "Developer"

Method 3: Upload a CSV file and convert it into JSON

Instead of using a fixed CSV input assigned to a program, this code allows users to choose the CSV file.

This code shows an HTML form with a file input to upload the input CSV file.

Once uploaded, the PHP script will read the CSV file content, prepare the array, and form the JSON output.

In a previous tutorial, we have seen how to convert a CSV into a PHP array.


if (isset($_POST["convert"])) {
    if ($_FILES['csv_file_input']['name']) {
        if ($_FILES['csv_file_input']["type"] == 'text/csv') {
            $jsonOutput = array();
            $csvFileContent = file_get_contents($_FILES['csv_file_input']['tmp_name']);
            $result = array_map("str_getcsv", explode("\n", $csvFileContent));
            $header = $result[0];
            $recordCount = count($result);
            for ($i = 1; $i < $recordCount; $i++) {
                // Associates the data with the string index in the header array
                $data = array_combine($header, $result[$i]);
                $jsonOutput[$i] = $data;
            header('Content-disposition: attachment; filename=output.json');
            header('Content-type: application/json');
            echo json_encode($jsonOutput);
        } else {
            $error = 'Invalid CSV uploaded';
    } else {
        $error = 'Invalid CSV uploaded';
<!DOCTYPE html>

    <title>Convert CSV to JSON</title>
        body {
            font-family: arial;

        input[type="file"] {
            padding: 5px 10px;
            margin: 30px 0px;
            border: #666 1px solid;
            border-radius: 3px;

        input[type="submit"] {
            padding: 8px 20px;
            border: #232323 1px solid;
            border-radius: 3px;
            background: #232323;
            color: #FFF;

        .validation-message {
            color: #e20900;
    <form name="frmUpload" method="post" enctype="multipart/form-data">
        <input type="file" name="csv_file_input" accept=".csv" /> 
        <input type="submit" name="convert" value="Convert">
        if (!empty($error)) 
            <span class="validation-message"><?php echo $error; ?></span>


This program writes the output JSON into a file and downloads it automatically to the browser.

Note: Both methods 2 and 3 require CSV input with a header column row to get good results.
output json file
View demo Download

Written by Vincy, a web developer with 15+ years of experience and a Masters degree in Computer Science. She specializes in building modern, lightweight websites using PHP, JavaScript, React, and related technologies. Phppot helps you in mastering web development through over a decade of publishing quality tutorials.

Leave a Reply

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

↑ Back to Top

Share this page