Create CSV from multidimensional array with fputcsv

OniJoshin picture OniJoshin · Feb 4, 2015 · Viewed 14.1k times · Source

I'm trying to get a multidimensional array into a csv file. data in the array is as such:

Array
(
 [0] => Array
    (
        [product_id] => 1111
        [name] => Alcatel One Touch Idol 2
        [keyword] => alcatel-one-touch-idol-2
        [options] => Array
            (
                [0] => Array
                    (
                        [price] => 54.0000
                    )

                [1] => Array
                    (
                        [price] => 42.0000
                    )

                [2] => Array
                    (
                        [price] => 10.0000
                    )

                [3] => Array
                    (
                        [price] => 
                    )

                [4] => Array
                    (
                        [price] => 
                    )

                [5] => Array
                    (
                        [price] => 
                    )

                [6] => Array
                    (
                        [price] => 
                    )

                [7] => Array
                    (
                        [price] => 
                    )

                [8] => Array
                    (
                        [price] => 
                    )

                [9] => Array
                    (
                        [price] => 
                    )

            )

    )

[1] => Array
    (...... etc)

I get all of the top level data, but then once it reaches the options array, i get Array to string conversion errors. So i have two issue, i firstly need to see why i am getting this error, and then i need to fputcsv all of this information on one line per product.

So far i have this to parse the array into a csv:

$output = fopen("php://output",'w') or die("Can't open php://output");
            header("Content-Type:application/csv"); 
            header("Content-  Disposition:attachment;filename=product_catalog.csv"); 
            $first_line = explode(",", $first_line);
            fputcsv($output, $first_line);
            foreach($csv as $file) {
                fputcsv($output, $file);
            }
            fclose($output) or die("Can't close php://output");

If anyone could help me i'd really appreciate that. regards.

Answer

Ja͢ck picture Ja͢ck · Feb 4, 2015

I would suggest to flatten each array first:

foreach ($csv as $file) {
    $result = [];
    array_walk_recursive($file, function($item) use (&$result) {
        $result[] = $item;
    });
    fputcsv($output, $result);
}

In each iteration it would create an array like this:

[1111, 'Alcatel One Touch Idol 2', 'alcatel-one-touch-idol-2', 54, 42, ...]