I need to convert an array with multiple results to a CSV file but am struggling to get a valid output . After some debugging I realized I am not generating a valid array list for fputcsv to iterate through .
First of all, here is an illustrative example of a var_dump of my array :
object(stdClass)#83 (3) { ["Username"]=> string(8) "username" ["FullName"]=> bool(false) ["ContactPhoneNumber"]=> bool(false) object(stdClass)#84 (3) { ["Username"]=> string(8) "username2" ["FullName"]=> bool(false) ["ContactPhoneNumber"]=> bool(false) object(stdClass)#85 (3) { ["Username"]=> string(8) "username3" ["FullName"]=> bool(false) ["ContactPhoneNumber"]=> bool(false)
And this is the code I have tried after some researching on how to convert an array to CSV :
$file = fopen($CsvFile, 'w'); fputcsv($file, array_keys($HeaderFields)); // Headers $data = array($DataRecord); foreach ($data as $row) { $row = []; array_walk_recursive($row, function ($item) use (&$row) { $row[] = $item; }); fputcsv($file, $row); } fclose($file);
I also tried to use the standard example from fputcsv :
$file = fopen($CsvFile, 'w'); $data = array($DataRecord) foreach ($data as $row) { fputcsv($file, $row); } fclose($file);
Obviously I am doing something very wrong and failing to produce the proper format for inserting multiple array lines in the csv file .
If I replace my $data array with this :
$data = array(array('Data 11', 'Data 12', 'Data 13', 'Data 14', 'Data 15'));
Then fputcsv works as expected .
So what I need is to convert my array into this format so fputcsv can iterate through it and save each line .
How could I achieve this ?
Thanks
Advertisement
Answer
Just cast the objects to arrays with (array)
:
$file = fopen($CsvFile, 'w'); fputcsv($file, get_object_vars(reset($data))); foreach ($data as $row) { fputcsv($file, (array)$row); } fclose($file);
If the object properties and $HeaderFields
are not the same then use $HeaderFields
instead.