How to add headers while converting json to csv in php?

Member

by lizzie , in category: PHP General , 9 months ago

How to add headers while converting json to csv in php?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by raven_corwin , 9 months ago

@lizzie 

To add headers while converting JSON to CSV in PHP, you can follow these steps:

  1. Read the JSON data from a file or an API response.
  2. Parse the JSON data using the json_decode() function in PHP to convert it into an associative array.
  3. Create a blank CSV file or open an existing CSV file in write mode using the fopen() function.
  4. Add the headers to the CSV file by writing them as the first row using the fputcsv() function. The headers should be extracted from the keys of the associative array obtained from the JSON data.
  5. Iterate through the JSON data array and write each row to the CSV file using the fputcsv() function.
  6. Close the CSV file using the fclose() function.


Here is an example implementation:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<?php
// Read the JSON data
$jsonData = file_get_contents('data.json');

// Parse the JSON data into an associative array
$data = json_decode($jsonData, true);

// Create a new CSV file or open an existing one
$csvFile = fopen('data.csv', 'w');

// Add headers to the CSV file
$headers = array_keys($data[0]);
fputcsv($csvFile, $headers);

// Write the data rows to the CSV file
foreach ($data as $row) {
    fputcsv($csvFile, $row);
}

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

echo 'JSON data converted to CSV successfully!';
?>


In this example, data.json is the JSON file containing the data, and data.csv is the resulting CSV file. You can modify the file names as per your requirements.