<?php
// $arraydata contains the mysql results in array
/*
example:
$data = array(
['firstname'] => 'Arman',
['lastname'] => 'Ortega',
['job'] => 'webdev',
) ;
$str = array_to_csv($data);
output:
firstname,lastname,job
Arman,Ortega,webdev
*/
function array_to_csv($arraydata, $delim = ",", $newline = "\n", $enclosure = '"')
{
if ( ! is_array($arraydata))
{
die('You must submit a valid array of csv data');
}
$out = '';
// Next blast through the result array and build out the rows
foreach ($arraydata as $row)
{
foreach ($row as $item)
{
$out .= $enclosure.str_replace($enclosure, $enclosure.$enclosure, $item).$enclosure.$delim;
}
$out = substr($out, 0, -1);
$out = rtrim($out);
$out .= $newline;
}
return $out;
}
Refactorings
No refactoring yet !
Christopher Wyllie
December 7, 2009, December 07, 2009 15:35, permalink
Think this might be a little less cluttered.
<?php
function array_to_csv(&$input, $delimeter=',', $linebreak="\n", $enclosure='"') {
if (!is_array($input))
die("Please provide an array of data.");
$keys = array_keys($input);
$values = array_values($input);
foreach ($values as $k => $v) {
// Not refactored
$values[$k] = $enclosure.str_replace($enclosure, $enclosure.$enclosure, $v).$enclosure;
}
print implode($delimeter, $keys);
print $linebreak;
print implode($delimeter, $values);
}
?>
Christopher Wyllie
December 7, 2009, December 07, 2009 15:37, permalink
Apologies, I thought it printed out the data, here's a modified version which returns it.
<?php
function array_to_csv(&$input, $delimeter=',', $linebreak="\n", $enclosure='"') {
if (!is_array($input))
die("Please provide an array of data.");
$keys = array_keys($input);
$values = array_values($input);
foreach ($values as $k => $v) {
// Not refactored
$values[$k] = $enclosure.str_replace($enclosure, $enclosure.$enclosure, $v).$enclosure;
}
$out = implode($delimeter, $keys);
$out .= $linebreak;
$out .= implode($delimeter, $values);
return $out;
}
?>
fain182.myopenid.com
December 7, 2009, December 07, 2009 18:51, permalink
why you use &$input instead of $input ? it doesn't seem necessary to me..
the example is evidently wrong, it lacks of enclosure.. or you don't need it?
cgwyllie
December 7, 2009, December 07, 2009 19:34, permalink
I used &$input simply to reduce some memory usage and save copying the entire input array into the function but it should work just the same with just $input.
Enclosure is there, and it's been copied directly from the original so I don't think it's wrong. If I've misunderstood the function, my apologies, but I have just tested it now and it's fine. Also, the input below was used because of syntax errors.
// PHP doesn't allow the [] brackets in this $data = array( ['firstname'] => 'Arman', ['lastname'] => 'Ortega', ['job'] => 'webdev', ) ; // This sample data was used for testing. $data = array( 'firstname' => 'Arman', 'lastname' => 'Ortega', 'job' => 'webdev', ) ;
Eineki
December 7, 2009, December 07, 2009 19:42, permalink
I think there $arraydata is an array of hashes.
Here there is the code, assuming that the $arraydata fields names
don't contain the enclosure character.
reference: http://www.creativyst.com/Doc/Articles/CSV/CSV01.htm
<?php
function array_to_csv($arraydata, $delimeter=',', $linebreak="\n", $enclosure='"') {
if (!is_array($arraydata)) {
trigger_error('You must submit a valid array of csv data', E_USER_ERROR);
}
$innerSeparator = $enclosure.$enclosure;
$fieldSeparator = $enclosure. $delimiter . $enclosure; //","
$rowSeparator = $enclosure. $linebreak . $enclosure; //"\n"
$csv=array();
// Format the header line
$csv[] = join($fieldSeparator, array_keys($arraydata[0]));
foreach ($arraydata as $row) {
$foreach ($row as $k=>$v) {
$row[$k]=str_replace($enclosure, $innerSeparator, $v);
}
$csv[] = join($fieldSeparator, $array_values($row));
}
return $enclosure . join($rowSeparator, $csv) . $enclosure;
}
Leafy
January 21, 2010, January 21, 2010 23:04, permalink
I think I got this right, based on the sample output / input.
<?php
function array_to_csv($data, $delim = ",", $newline = "\n", $enclosure = '"') {
if(!is_array($data))
trigger_error('You must submit a valid array of csv data', E_USER_ERROR);
$header = array_keys($data);
$footer = array_values($data);
$output = $enclosure . implode($header, ($enclosure . $delim . $enclosure)) . $enclosure . $newline;
$output .= $enclosure . implode($footer, ($enclosure . $delim . $enclosure)) . $enclosure . $newline;
return $output;
}
/*
leafy@leafy-desktop:~/refactoring$ php 1120.php
"firstname","lastname","job"
"Arman","Ortega","webdev"
leafy@leafy-desktop:~/refactoring$
*/
?>
incidence
March 17, 2010, March 17, 2010 14:25, permalink
<?php
function array_to_csv($data, $delim = ",") {
return implode($delim,$data);
}
?>
Chris
March 21, 2010, March 21, 2010 04:39, permalink
PHP as of 5.1.0 supports in-memory filestreams which let us use functions like fputcsv and fgetcsv work a lot cooler. I am also taking the original posters word on it being from MySQL instead of the input/output he provided (and based on reading his actual code).
<?PHP
// Requires PHP 5.1.0 at least; I won't do the check pragmatically though.
function array_to_csv ($data, $delim = ',', $enclosure = '"')
{
if (empty($data) && !is_array($data)) {
return false;
}
$sock = fopen('php://memory', 'w+');
if ($sock === false) {
return false;
}
// length written
$length = 0;
foreach ($data as $row) {
$tmp = fputcsv($sock, $row, $delim, $enclosure);
if ($tmp === false) {
return false;
}
$length += $tmp;
}
fseek($sock, 0);
$csv = fread($sock, $length);
fclose($sock);
return $csv;
}
hi guys, is there other better way to generate csv string from the mysql resultset ?
Ive implemented one solution below, can you refactore it ?
Thanks