1

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

  • 1
    You have an object not array which is why it's not working. You need to convert each object to an array to use with `fputcsv`. Take a look at https://stackoverflow.com/questions/52933052/php-fputcsv-cannot-use-object-of-type-stdclass-as-array – cOle2 Feb 12 '21 at 18:06

1 Answers1

1

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.

AbraCadaver
  • 78,200
  • 7
  • 66
  • 87
  • Thanks so much, this works perfect !!! I have been struggling with this for hours as I just started with php so saved my day :) – Optimus Servers Feb 12 '21 at 20:05