In this tutorial, you will learn how to convert a CSV file to a JSON file in PHP. CSV (Comma Separated Values) files store tabular data and are easily readable by humans. On the other hand, JSON (JavaScript Object Notation) is a lightweight data-interchange format that is widely used in web applications.



Why Convert CSV to JSON?

You may want to convert CSV files to JSON for several reasons. First, JSON is a more flexible format than CSV, allowing you to store complex data structures such as arrays and nested objects. Second, JSON is easier to parse and manipulate than CSV, as it can be directly converted into JavaScript objects. Third, JSON is widely used in web development, especially for building REST APIs.

Converting CSV to JSON using PHP

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

Step 1: Create a CSV File

Create a sample CSV file with some dummy data. In this tutorial, We have used the following data:

Name,Age,Gender
Alex,30,Male
Jane,25,Female

Save this file as "data.csv" in the same directory as your PHP script.

Step 2: Read the CSV File

The second step is to read the contents of the CSV file using PHP. 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('data.csv', 'r');
$headers = fgetcsv($fp); // Get column headers

$data = array();
while (($row = fgetcsv($fp))) {
    $data[] = array_combine($headers, $row);
}
fclose($fp);
print_r($data);

Explanation:

  • The CSV file is first opened in read mode in the above example using the fopen function.
  • Next, the "fgetcsv" function reads the first line of the CSV file (which contains the headers) and stores it in the "$headers" variable.
  • Next, an empty array named "$data" is created.
  • In the next step, a while loop reads each row of data using the "fgetcsv" function.
  • Within the while loop, the "array_combine" function combines the header and row data into an associative array and then appends it to the "$data" array.
  • After reading all the lines in the while loop, the file is closed using the "fclose" function.
  • Finally, the "$data" array is printed using the "print_r" function for debugging purposes.

Step 3: Convert to JSON

Once the CSV data is read and converted to a PHP array, the built-in PHP function "json_encode" converts it to JSON format.

Example:

$json = json_encode($data, JSON_PRETTY_PRINT);

In the above 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 JSON file

The last step is to write the JSON data into a JSON file. To do this, we can use the "file_put_contents" function.

Example:

$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
$fp = fopen('data.csv', 'r');
$headers = fgetcsv($fp); // Get column headers

$data = array();
while (($row = fgetcsv($fp)) !== false) {
    $data[] = array_combine($headers, $row);
}
fclose($fp);

$json = json_encode($data, JSON_PRETTY_PRINT);

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

That's it! You should now have a JSON file named "data.json" that contains the same data as the CSV file. You can modify the code to handle different CSV file formats and data structures.

Output:

[
    {
        "Name": "Alex",
        "Age": "30",
        "Gender": "Male"
    },
    {
        "Name": "Jane",
        "Age": "25",
        "Gender": "Female"
    }
]


Found This Page Useful? Share It!
Get the Latest Tutorials and Updates
Join us on Telegram