1cd9c8984f2fdeb996130d54d62a98d9

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

<?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 !

9e33e22c685b6e9d43000c019123bcd3

Christopher Wyllie

December 7, 2009, December 07, 2009 15:35, permalink

1 rating. Login to rate!

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);
}

?>
9e33e22c685b6e9d43000c019123bcd3

Christopher Wyllie

December 7, 2009, December 07, 2009 15:37, permalink

1 rating. Login to rate!

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;
}

?>
1bf59120892e34eb60836725566c6e55

fain182.myopenid.com

December 7, 2009, December 07, 2009 18:51, permalink

1 rating. Login to rate!

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?

B38e721883fd3ce1fa6c66fc5547ab57

cgwyllie

December 7, 2009, December 07, 2009 19:34, permalink

No rating. Login to rate!

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',
) ;
5a00a3a98dcf6f9cd717440fd2b606e5

Eineki

December 7, 2009, December 07, 2009 19:42, permalink

No rating. Login to rate!

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;
}
E88fb20ff4a97b4859ad9c25b8d6250e

Leafy

January 21, 2010, January 21, 2010 23:04, permalink

No rating. Login to rate!

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$
*/
?>
Af941b609e976c37a10a38d38f9eb203

incidence

March 17, 2010, March 17, 2010 14:25, permalink

No rating. Login to rate!
<?php
function array_to_csv($data, $delim = ",") {
	return implode($delim,$data);
}
?>
91239a954fae9afc4ecdd460203df745

Chris

March 21, 2010, March 21, 2010 04:39, permalink

No rating. Login to rate!

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;
}

Your refactoring





Format Copy from initial code

or Cancel