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
  • 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 stackoverflow.com/questions/52933052/… Commented Feb 12, 2021 at 18:06

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks so much, this works perfect !!! I have been struggling with this for hours as I just started with php so saved my day :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.