Wednesday, April 24, 2024
HomePHPConvert PHP CSV to JSON

Convert PHP CSV to JSON


by Vincy. Final modified on March seventeenth, 2023.

JSON format is a extensively used format whereas working with API growth. A lot of the current API responses are in JSON format.

Changing CSV content material right into a JSON format is straightforward in PHP. On this article, we are going to see totally different strategies of reaching this conversion.

Fast instance

<?php 
$csvFileContent= file_get_contents("animals.csv");
// Converts the CSV file content material into line array 
$csvLineArray = explode("n", $csvFileContent);
// Kinds row leads to an array format
$outcome = array_map("str_getcsv", $csvLineArray);
$jsonObject = json_encode($outcome);
print_r($jsonObject);
?>

The above fast instance in PHP converts the CSV file content material into JSON with few strains of code.

  1. First, it reads the .csv file content material utilizing the PHP file_get_contents() operate.
  2. It explodes the CSV row by the brand new line (n) escape sequence.
  3. Then, it iterates the road array and reads the road information of the CSV row.
  4. Lastly, the resultant CSV row array is transformed to JSON utilizing the json_encode() operate.

In step 3, the iteration occurs with a single line of code. This line maps the array to name  PHP str_getcsv to parse and convert the CSV strains into an array.

After we noticed the strategies of studying a CSV file, we created an instance utilizing str_getcsv operate.

The beneath enter file is saved and used for this PHP instance.

Enter CSV

Id,Title,Sort,Function
1,Lion,Wild,"Lazy Boss"
2,Tiger,Wild,CEO
3,Jaguar,Wild,Developer

Output JSON

This PHP fast instance shows the beneath JSON output on the browser.

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

Within the following sections, we are going to see two extra examples of changing CSV information into JSON.

  1. Methodology 2: Convert CSV (containing header) right into a JSON (associating the column=>worth pair)
  2. Methodology 3: Add a CSV file and convert it into JSON

upload and convert csv to json

Methodology 2: Convert CSV (containing header) right into a JSON (associating the column=>worth pair)

This instance makes use of a CSV string as its enter as an alternative of a file.

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

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

This loop prepares an associative array containing the CSV information.

Within the closing step, the json_encode() operate converts the associative array and writes it into an output JSON file.

<?php
$csvString = "Id,Title,Sort,Function
1,Lion,Wild,Boss
2,Tiger,Wild,CEO
3,Jaguar,Wild,Developer";

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

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

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

Output – The animal.json file

That is the output written to the animal.json file by way of this PHP program.

{
    "1": {
        "Id": "1",
        "Title": "Lion",
        "Sort": "Wild",
        "Function": "Boss"
    },
    "2": {
        "Id": "2",
        "Title": "Tiger",
        "Sort": "Wild",
        "Function": "CEO"
    },
    "3": {
        "Id": "3",
        "Title": "Jaguar",
        "Sort": "Wild",
        "Function": "Developer"
    }
}

Methodology 3: Add a CSV file and convert it into JSON

As an alternative of utilizing a hard and fast CSV enter assigned to a program, this code permits customers to decide on the CSV file.

This code exhibits an HTML type with a file enter to add the enter CSV file.

As soon as uploaded, the PHP script will learn the CSV file content material, put together the array, and type the JSON output.

In a earlier tutorial, now we have seen the right way to convert a CSV right into a PHP array.

upload-and-convert-csv-to-json.php

<?php
if (isset($_POST["convert"])) {
    if ($_FILES['csv_file_input']['name']) {
        if ($_FILES['csv_file_input']["type"] == 'textual content/csv') {
            $jsonOutput = array();
            $csvFileContent = file_get_contents($_FILES['csv_file_input']['tmp_name']);
            $outcome = array_map("str_getcsv", explode("n", $csvFileContent));
            $header = $outcome[0];
            $recordCount = rely($outcome);
            for ($i = 1; $i < $recordCount; $i++) {
                // Associates the info with the string index within the header array
                $information = array_combine($header, $outcome[$i]);
                $jsonOutput[$i] = $information;
            }
            header('Content material-disposition: attachment; filename=output.json');
            header('Content material-type: utility/json');
            echo json_encode($jsonOutput);
            exit();
        } else {
            $error="Invalid CSV uploaded";
        }
    } else {
        $error="Invalid CSV uploaded";
    }
}
?>
<!DOCTYPE html>
<html>

<head>
    <title>Convert CSV to JSON</title>
    <type>
        physique {
            font-family: arial;
        }

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

        enter[type="submit"] {
            padding: 8px 20px;
            border: #232323 1px strong;
            border-radius: 3px;
            background: #232323;
            shade: #FFF;
        }

        .validation-message {
            shade: #e20900;
        }
    </type>
</head>
<physique>
    <type title="frmUpload" methodology="put up" enctype="multipart/form-data">
        <enter sort="file" title="csv_file_input" settle for=".csv" /> 
        <enter sort="submit" title="convert" worth="Convert">
        <?php
        if (!empty($error)) 
        { 
        ?>
            <span class="validation-message"><?php echo $error; ?></span>
        <?php 
        } 
        ?>
    </type>
</physique>
</html>

Output:

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

Word: Each strategies 2 and three require CSV enter with a header column row to get good outcomes.
output json file
Obtain

↑ Again to Prime

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments