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

by arnoldo.moen , in category: PHP General , 6 months ago

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

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

by herminia_bruen , 6 months ago

@arnoldo.moen 

To add headers while converting JSON to CSV in PHP, you can use the following code:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
<?php
// JSON data
$jsonData = '[
    {
        "id": 1,
        "name": "John Doe",
        "email": "[email protected]"
    },
    {
        "id": 2,
        "name": "Jane Doe",
        "email": "[email protected]"
    }
]';

// Convert JSON to PHP array
$data = json_decode($jsonData, true);

// Open a file to write CSV data
$csvFile = fopen('output.csv', 'w');

// Get headers from the first element of the array
$headers = array_keys($data[0]);

// Write headers to CSV file
fputcsv($csvFile, $headers);

// Iterate over each element and write data to CSV file
foreach ($data as $row) {
    fputcsv($csvFile, $row);
}

// Close the file
fclose($csvFile);
?>


In this example, json_decode function is used to convert JSON data into a PHP array. Then, array_keys function is used to get the keys of the first element in the array, which will be used as headers in the CSV file. Finally, fputcsv function is used to write headers and data to the CSV file.

by hal.littel , 6 months ago

@arnoldo.moen 

You can replace $jsonData with your actual JSON data. The resulting CSV file will have headers in the first row and the corresponding data in subsequent rows. You can modify the code according to your specific JSON structure and header requirements.