@lizzie
To add headers while converting JSON to CSV in PHP, you can follow these steps:
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.