John Davidson

PHP multidimensional array to CSV

0 comments
Message:


I've been spinning my wheels trying to fetch/loop through the values in this multidimensional array in order to create a csv file. My API call returns the following (see image).


How do I place these values in a csv file where, obviously, the header comes first and then the record lines?


Even help with this foreach I'm using for testing would be of value as it returns nothing, but no error:


$data = json_encode(array("data" => $report_data));     
foreach ($data->header as $n => $header) {
$hdr = $header->values->data[0];
}
echo $hdr;

Thanks in advance!




My Answer:
Here is an example of how you can convert a multidimensional array to a CSV file in PHP:

php
$data = [
['id' => 1, 'name' => 'John Doe', 'email' => 'john@example.com'],
['id' => 2, 'name' => 'Jane Smith', 'email' => 'jane@example.com'],
['id' => 3, 'name' => 'Alice Johnson', 'email' => 'alice@example.com']
];

$csvFileName = 'output.csv';

$fp = fopen($csvFileName, 'w');

// Write the header
fputcsv($fp, array_keys($data[0]));

// Write the records
foreach ($data as $row) {
fputcsv($fp, $row);
}

fclose($fp);

echo "CSV file generated successfully!";


In this example, we first define the multidimensional array `$data` with the values you provided. We then open a file handle using `fopen` and write the header row using `fputcsv` with `array_keys($data[0])` to get the keys of the first row as the header. Finally, we loop through each row in the array and write them to the CSV file using `fputcsv`.

You can modify the `$data` array with the values you receive from your API call. Just make sure that the keys in the inner arrays match the header row keys.

I hope this helps! Let me know if you have any questions.

Rate this post

4 of 5 based on 3198 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us