Convert a CSV file into JSON using PHP.

This is a short tutorial on how to convert the data in a CSV file into a JSON string format. For this example, we will assume that we have a CSV file called names.csv and that it contains the following data:

Jack,Ireland,34
John,USA,19
Michelle,Spain,23
Robert,USA,38
Lisa,United Kingdom,40

As you can see – it’s pretty simple and straight-forward. To convert it into JSON, we will need to read the CSV file using PHP before converting it into JSON.

Here’s a quick example using the CSV file above:

<?php

//Open our CSV file using the fopen function.
$fh = fopen("names.csv", "r");

//Setup a PHP array to hold our CSV rows.
$csvData = array();

//Loop through the rows in our CSV file and add them to
//the PHP array that we created above.
while (($row = fgetcsv($fh, 0, ",")) !== FALSE) {
    $csvData[] = $row;
}

//Finally, encode our array into a JSON string format so that we can print it out.
echo json_encode($csvData);

Explained:

  1. We opened our CSV file using the fopen function. We set the second parameter to “r” because we only need to read the file – not modify it.
  2. We created a PHP array called $csvData. This array will contain the data from our CSV file.
  3. We looped through the rows in our CSV file using the fgetcsv function and added them to our $csvData array.
  4. Finally, once our loop is completed, we convert the CSV data into a JSON string by using the function json_encode.

Hopefully, you found this tutorial to be helpful. If you want to do it the other way around, then you can check out this tutorial on converting JSON into a CSV file using PHP.