Tutorial – Convert CSV To JSON Using PHP

To convert a CSV file to JSON using PHP, you can use the following approach:

  1. First, open the CSV file using the fopen function and read the contents using fgetcsv. This will read each row of the CSV file as an array.
  2. Next, you can loop through the rows of the CSV file and convert each row to a JSON object by specifying the header row as the keys and the corresponding values as the values for each key.
  3. To create the JSON object for each row, you can use the array_combine function to combine the keys and values into an associative array, and then use the json_encode function to convert the array to a JSON object.
  4. You can then add each JSON object to an array, which will contain all the JSON objects for each row of the CSV file.

Here’s an example of how you can implement this in PHP:


<?php

// Open the CSV file
$csv = fopen('data.csv', 'r');

// Read the header row
$headers = fgetcsv($csv);

// Initialize an array to store the JSON objects
$json_objects = array();

// Loop through the rows of the CSV file
while ($row = fgetcsv($csv)) {
// Create a JSON object for the current row
$json_object = json_encode(array_combine($headers, $row));
// Add the JSON object to the array
$json_objects[] = $json_object;
}

// Close the CSV file
fclose($csv);

// Print the array of JSON objects
print_r($json_objects);

?>

This will read the CSV file and convert it to an array of JSON objects, with the header row as the keys and the corresponding values as the values for each key.

Was this helpful?

1 / 0

Leave a Reply 0

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