Convert CSV to JSON in PHP

In this tutorial, you will learn how to convert CSV data or files into a JSON object in PHP.

You should also read the following PHP JSON post:

Sometimes it may be necessary to convert data from CSV format to JSON format. In this guide, we will discuss how to convert CSV to JSON using PHP.

How to Convert CSV to JSON File using PHP

By using the following steps, you can convert CSV (Comma Separated Values) to JSON (JavaScript Object Notation) in PHP, follow these steps:

  • Step 1: Create a CSV File
  • Step 2: Read the CSV File
  • Step 3: Convert CSV File to JSON File
  • Step 4: Write Data in JSON file

Step 1: Create a CSV File

Let you have one CSV file and its URL https://docs.google.com/spreadsheets/d/e/2PACX-1vTEKCTdbMgSEt7UCymQ956PIYsHei51gpCtPou4VGugKRztJVuZSNuDXKDrdDiZxx6-Ebepte8P6OlG/pub?output=csv. It contains the name, age, email id.

This file looks like below:

Save this file as “abcFile.csv” in the same directory as your PHP script.

Step 2: Read the CSV File

Then, you need to read csv file data. So, You can use the built-in PHP function “fopen” to open the file and “fgetcsv” to read data from the CSV file.

Example:

$fp = fopen('abcFile.csv', 'r');
$headers = fgetcsv($fp); // Get column headers
$data = array();
while (($row = fgetcsv($fp))) {
    $data[] = array_combine($headers, $row);
}
fclose($fp);
print_r($data);

Step 3: Convert CSV File to JSON File

Once you have read CSV data file in php code, now you need to convert it to json data or PHP array. So, you can use the built-in PHP function “json_encode” converts it to JSON format.

// convert array to json php using the json_encode()
$arrayToJson = json_encode($newArray);
// print converted csv value to json
echo $arrayToJson;

In the above given php code, the “$data” array is passed to “json_encode” function with the option “JSON_PRETTY_PRINT” to format the JSON output with indentation and line breaks.

Step 4: Write Data in JSON file

In the final step, you need to write into json file. So for that, you can use the “file_put_contents” function.

$output_filename = 'data.json';
file_put_contents($output_filename, $json);

In the above code, we pass the “$output_filename” and “$json” to the “file_put_contents” function, which writes the data to the file.

Here is the complete code to convert CSV file to JSON file using PHP by writing all the code together:

Example:

<?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 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 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 array
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;
?>

Conclusion

In this article, you have learned how to convert CSV files to JSON using PHP.

Recommended PHP Tutorials

  1. Autocomplete Search Box in PHP MySQL
  2. Compare Arrays PHP | PHP array_diff() Function
  3. Get, Write, Read, Load, JSON File from Url PHP
  4. Functions: Remove First Character From String PHP
  5. Remove Specific/Special Characters From String In PHP
  6. How to Replace First and Last Character From String PHP
  7. Reverse String in PHP
  8. Array Push, POP PHP | PHP Array Tutorial
  9. PHP Search Multidimensional Array By key, value and return key
  10. json_encode()- Convert Array To JSON | Object To JSON PHP
  11. PHP remove duplicates from multidimensional array
  12. PHP Remove Duplicate Elements or Values from Array PHP
  13. Get Highest Value in Multidimensional Array PHP
  14. PHP Get Min or Minimum Value in Array
  15. String PHP to Uppercase, Lowercase & First Letter Uppercase
  16. PHP: isset() vs empty() vs is_null()
  17. Chunk_split PHP Function Example
  18. PHP Function: Date and Time With Examples
  19. Reverse Number in PHP | PHP Tutorial

AuthorDevendra Dode

Greetings, I'm Devendra Dode, a full-stack developer, entrepreneur, and the proud owner of Tutsmake.com. My passion lies in crafting informative tutorials and offering valuable tips to assist fellow developers on their coding journey. Within my content, I cover a spectrum of technologies, including PHP, Python, JavaScript, jQuery, Laravel, Livewire, CodeIgniter, Node.js, Express.js, Vue.js, Angular.js, React.js, MySQL, MongoDB, REST APIs, Windows, XAMPP, Linux, Ubuntu, Amazon AWS, Composer, SEO, WordPress, SSL, and Bootstrap. Whether you're starting out or looking for advanced examples, I provide step-by-step guides and practical demonstrations to make your learning experience seamless. Let's explore the diverse realms of coding together.

Leave a Reply

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