1

I have an array $csvRows like the following. I want to export that array as CSV.

Array
(
    [0] => SingleModule Object
        (
            [module:SingleModule:private] => Module Object
                (
                    [name:Module:private] => SimpleXMLElement Object
                        (
                            [0] => some string
                        )

                    [position:Module:private] => SimpleXMLElement Object
                        (
                            [0] => 1000
                        )

                    [config:Module:private] => SimpleXMLElement Object
                        (
                        )

                )

            [moduleMeta:SingleModule:private] => ModuleMeta Object
                (
                    [description:ModuleMeta:private] => description text
                    [featureOrUseCase:ModuleMeta:private] => feature or usecase text
                    [inputParam:ModuleMeta:private] => input Parameter text
                    [changedParam:ModuleMeta:private] => changed Parameter text
                    [newOutputParam:ModuleMeta:private] => new Output Param text
                    [commentOrNote:ModuleMeta:private] => comments Or Note text
                )

        )

    [1] => SingleModule Object
         (etc...)

I have already tried the solution, which I found in this link. Here is my code sample:

$fileName = "../../data/modules.csv";
$output = fopen($fileName, 'w+');
foreach ( $csvRows as $file ) {
    $result = [ ];
    array_walk_recursive($file, function ($item) use (&$result) {
        $result [] = $item;
    });
    fputcsv($output, $result);
}
fclose($output);

Then I get the following error:

PHP Recoverable fatal error:  Object of class Module could not be converted to string ...in line where fputcsv is.

I have temporarily solved the problem by manually creating a straightforward array like the following, which I found in this link:

 $csvRows = array(
        array( 'row_1_col_1', 'row_1_col_2', 'row_1_col_3' ),
        array( 'row_2_col_1', 'row_2_col_2', 'row_2_col_3' ),
        array( 'row_3_col_1', 'row_3_col_2', 'row_3_col_3' ),
    );

But I want to export my actual $csvRows array of objects as CSV. I am a newbie programmer, so any suggestion and help would highly appreciated.

sumion
  • 137
  • 1
  • 2
  • 14
  • Hi, I have tried your suggestion like the following: `$str = json_encode($csvRows); $csvRows = json_decode($str, true); $fp = fopen("../../data/modules.csv", 'w+'); foreach ( $csvRows as $column ) { fputcsv($fp, $column); } fclose($fp);` but I only have an empty csv file. Any idea? – sumion Sep 25 '17 at 14:14

1 Answers1

1

Try the following solution:

$str = json_encode($csvRows);
$csvRows = json_decode($str, true);
foreach ($csvRows as $file) {
    $result = [];
    array_walk_recursive($file, function($item) use (&$result) {
        $result[] = $item;
    });
    fputcsv($output, $result);
}

Just convert all those object to associative array. And then add the array to CSV. Use JsonSerializable interface on SingleModule class and configure the following method:

class SingleModule implements JsonSerializable {
//YOUR CODE
    public function jsonSerialize() {
        return get_object_vars($this);
    }
}
mega6382
  • 9,211
  • 17
  • 48
  • 69
  • Hi, I have tried your suggestion like the following: `$str = json_encode($csvRows); $csvRows = json_decode($str, true); $output = fopen("../../data/modules.csv", 'w+'); foreach ( $csvRows as $file ) { $result = [ ]; array_walk_recursive($file, function ($item) use (&$result) { $result [] = $item; }); fputcsv($output, $result); }` but I only have an empty csv file. Any idea? – sumion Sep 25 '17 at 14:24
  • @IqbalNazir it might be due to every property of the objects being `private`. you can't access it outside the class. – mega6382 Sep 25 '17 at 14:29
  • yes, you are right. It's working when I have changed access modifier to `public`. Thanks for that. But I want to keep them private, and also export them as CSV. Any idea? – sumion Sep 25 '17 at 14:39
  • @IqbalNazir for that have a look at [ReflectionClass](http://php.net/manual/en/reflectionclass.getproperties.php) – mega6382 Sep 25 '17 at 14:46
  • @IqbalNazir I have provided a solution for this in my answer. – mega6382 Sep 25 '17 at 15:09
  • hi mega6382, I could solve the problem keeping my properties private. I used getter functions, then I had the values I needed. In the end, it was working simple with fputcsv. Thanks for your response. – sumion Sep 26 '17 at 15:21
  • @IqbalNazir No problem. Did you try my way? just to check? – mega6382 Sep 26 '17 at 16:01
  • @IqbalNazir So, was `json_encode` part atleast helpful to you? – mega6382 Sep 27 '17 at 10:53
  • `json_encode/decode` was working along with `array_walk_recursive` function. Then I tried simple `fputcsv` with the array of values and removed `json_encod/decode` and `array_walk_recursive`. It is also working. – sumion Sep 27 '17 at 13:42