create a csv file now working

hi
i have an array i need to export and download as a csv file. this is the array i got:
        array_to_csv_download(array(
            array( 'y' => "2006" ,'a' => rand( 2, 145 ) , 'b' => rand( 5, 55 ) ) ,
            array( 'y' => "2007" ,'a' => 75 , 'b' => 65 ) ,
            array( 'y' => "2008" ,'a' => 60 , 'b' => 40 ) ,
            array( 'y' => "2009" ,'a' => 50 , 'b' => 40 ) ,
            array( 'y' => "2010" ,'a' => 35 , 'b' => 90 ) ,
            array( 'y' => "2011" ,'a' => 48 , 'b' => 55 ) ,
            "lastweekwh.csv" 
            )
        );

Open in new window


and this is the function:
function array_to_csv_download($array, $filename = "export.csv", $delimiter=";") {
    header('Content-Type: application/csv');
    header('Content-Disposition: attachement; filename="'.$filename.'";');

 
    $f = fopen('php://output', 'w');

    //var_dump($array);
    

    foreach ($array as $line) {
        fputcsv($f, $line, $delimiter);
    }
}

Open in new window


the error i get is that fputcsv() expect parameter 2 to be array, string given. i don't understand why? i pass an array.

best regards
LVL 1
derridaAsked:
Who is Participating?
 
Ray PaseurCommented:
This seems to work; not sure why your example is having trouble.  It may be "lastweekwh.csv"  in the input array.  You might want to check the spelling of "attachment" and decide if the semi-colon delimiter is useful (it does not play well with Excel).

<?php // demo/temp_derrida.php

/**
 * See http://www.experts-exchange.com/Programming/Languages/Scripting/PHP/Q_28631705.html
 */
error_reporting(E_ALL);

$data = array
( array( 'y' => "2006" ,'a' => rand( 2, 145 ) , 'b' => rand( 5, 55 ) )
, array( 'y' => "2007" ,'a' => 75 , 'b' => 65 )
, array( 'y' => "2008" ,'a' => 60 , 'b' => 40 )
, array( 'y' => "2009" ,'a' => 50 , 'b' => 40 )
, array( 'y' => "2010" ,'a' => 35 , 'b' => 90 )
, array( 'y' => "2011" ,'a' => 48 , 'b' => 55 )
)
;

header('Content-Type: application/csv');
header('Content-Disposition: attachment; filename="xyz.csv";');

$delimiter = ';';
$f = fopen('php://output', 'w');
foreach ($data as $line)
{
    fputcsv($f, $line, $delimiter);
}

Open in new window

0
 
derridaAuthor Commented:
hi
this is done by an ajax call. now the browser doesn't ask to download it. but it was the file name in the array. thanks
0
 
Ray PaseurCommented:
Great!  Thanks for the points, ~Ray
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.