Papermashup

Subscribe


Tweets


"Is there ever a time that @DFS doesn't have a sale on?"

@ashleyford 3 days ago

"RT @lalpra: Galaxy Note 7 Unboxing https://t.co/FM8gZmqpBK"

@ashleyford 5 days ago

Designer and web developer, Co-founder and Technical Director at Harkable.com. Previously I worked at Spotify, MySpace and InMobi. Contact me - ashley[at]papermashup.com

Papermashup

PHP array to CSV Function

Download a CSV of data from a PHP array

AshleyAshley

Sometimes we need to export and convert data from a database into a CSV format that can be downloaded and manipulated for other purposes. This function will loop through the multi dimensional array and convert the data to CSV format and output the download to the browser forcing the headers to download the file.

The Code



function convert_to_csv($input_array, $output_file_name, $delimiter)
{
$temp_memory = fopen('php://memory', 'w');
// loop through the array
foreach ($input_array as $line) {
// use the default csv handler
fputcsv($temp_memory, $line, $delimiter);
}

fseek($temp_memory, 0);
// modify the header to be CSV format
header('Content-Type: application/csv');
header('Content-Disposition: attachement; filename="' . $output_file_name . '";');
// output the file to be downloaded
fpassthru($temp_memory);
}

$array_of_data = Array(
Array(1,
'Dave',
'Smith',
'dave[at]dave.com'
),
Array(2,
'Sam',
'Adams',
'sam[@]adams.com'
),
Array(3,
'Gary',
'Davis',
'gary[at]davis.com'
)
);

convert_to_csv($array_of_data, 'data_as_csv.csv', ',');

Designer and web developer, Co-founder and Technical Director at Harkable.com. Previously I worked at Spotify, MySpace and InMobi. Contact me - ashley[at]papermashup.com

Comments 3
  • Rever Eye
    Posted on

    Rever Eye Rever Eye

    Reply Author

    Nice post.
    Thank you.


  • Murtuza
    Posted on

    Murtuza Murtuza

    Reply Author

    Hey there, thanks for this post, I’m new to the Data arena and these kinda posts help!


  • JessicaLillis
    Posted on

    JessicaLillis JessicaLillis

    Reply Author

    Great Ashley ! I like your activities. Go ahead..Best of luck.