To convert a CSV file to JSON using PHP, you can use the following approach:
- First, open the CSV file using the
fopen
function and read the contents usingfgetcsv
. This will read each row of the CSV file as an array. - 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.
- 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 thejson_encode
function to convert the array to a JSON object. - 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