Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@taichunmin
Created June 4, 2014 18:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save taichunmin/e921bb8e08539eef9e6a to your computer and use it in GitHub Desktop.
Save taichunmin/e921bb8e08539eef9e6a to your computer and use it in GitHub Desktop.
<?php
/*
Example:
$arr = array(
'a' => '123',
'b' => '456',
);
$csv = iconv('UTF-8','CP950//IGNORE',tai_array2csv($arr));
參考: https://gist.github.com/3422591
*/
function tai_array2csv($fields, $delimiter = ',', $enclosure = '"', $lineseparate = "\r\n")
{
$csvstr = '';
foreach( $fields as $d )
{
if(strlen($csvstr) != 0) $csvstr .= $delimiter;
$d = str_replace($enclosure, $enclosure.$enclosure, $d);
if ( strpbrk($d, " \t\n\r".$delimiter.$enclosure.$lineseparate)!==false || strpos($d, 0)!==false ) {
$csvstr .= $enclosure.$d.$enclosure;
} else {
$csvstr .= $d;
}
}
return $csvstr . $lineseparate;
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment