Page 1 of 1

export array values to csv ??

Posted: Mon Jun 04, 2007 3:57 am
by PHPycho
Hello forums !!
i would like to know how to export the data in .csv format ?
suppose i had an array holding values:

Code: Select all

$data_arr[$i][0] = "xx";
$data_arr[$i][0] = "xx";
$data_arr[$i][0] = "xx";
$data_arr[$i][0] = "xx";
where $i varies from 0 to n

I would like to export this data in .csv format,
how could this be accomplished ?
Thanks in advance to all of you

Posted: Mon Jun 04, 2007 7:27 am
by superdezign
CSV is comma separated, right? You could join your arrays, then implode() them using a comma. Then, create a CSV file with your result as it's content.

Posted: Mon Jun 04, 2007 1:40 pm
by timvw
To make sure that the CSV remains valid i would recommend to wrap all the values in quotes...

Posted: Mon Jun 04, 2007 2:58 pm
by maliskoleather
with some forloops, implode, and a little creativity, this is defenantly feasable.
just be sure to wrap your values in double quotes, and as long as you understant the formatting for .CSV, you should be fine.

I just did this a few weeks ago in the opposite direction... i turned .CSV files into arrays... It's not really as complex as it may seem ;)

Posted: Tue Jun 05, 2007 6:24 am
by PHPycho
feyd | Please use

Code: Select all

,

Code: Select all

and [syntax="..."] tags where appropriate when posting code. Your post has been edited to reflect how we'd like it posted. Please read:  [url=http://forums.devnetwork.net/viewtopic.php?t=21171]Posting Code in the Forums[/url] to learn how to do it too.[/color]

Code: Select all

<?php
# data stored in array
$data_arr[$i][0] = "xx";
$data_arr[$i][0] = "xx";
$data_arr[$i][0] = "xx";
$data_arr[$i][0] = "xx";

# Export Start
header('Content-type: application/x-csv');
header('Content-Disposition: attachment; filename='filename.csv');
header('Content-Description: PHP Generated Data');
for($i = 0; $i < count($data_arr); $i++){
	echo generateCsv($data_arr[$i]);
}
exit(0);
//print_r($data_arr);

function generateCsv($data, $sep = ',', $quot = '"'){ 
	$csv_data = ""; 
	foreach($data as $val){ 		
		$csv_data .= $sep; 
		$csv_data .= $quot.$val.$quot; 
	} 
	return ltrim($csv_data,",")."\r\n"; 
}
?>
its working.....would like to comment on my code
any further improvements ?
Thanks in advance to all of you


feyd | Please use

Code: Select all

,

Code: Select all

and [syntax="..."] tags where appropriate when posting code. Your post has been edited to reflect how we'd like it posted. Please read:  [url=http://forums.devnetwork.net/viewtopic.php?t=21171]Posting Code in the Forums[/url] to learn how to do it too.[/color]

Posted: Tue Jun 05, 2007 6:31 am
by onion2k
If your data contains a " then your csv is going to break.

Posted: Tue Jun 05, 2007 7:31 am
by feyd
fputcsv() may be of interest. There are PHP 4 versions available too.