public static function encode($data, $omit = null, $delim = ',', $esc = '"', $dt = null)
{
$output = '';
$tempAry = array();
$headerAry = array();
if (null === $omit) {
$omit = array();
} else {
if (!is_array($omit)) {
$omit = array($omit);
}
}
// Initialize and clean the header fields.
foreach ($data as $ary) {
$tempAry = array_keys((array) $ary);
}
foreach ($tempAry as $key => $value) {
if (!in_array($value, $omit)) {
$v = (string) $value;
if (strpos($v, $esc) !== false) {
$v = str_replace($esc, $esc . $esc, $v);
}
if (strpos($v, $delim) !== false) {
$v = $esc . $v . $esc;
}
$headerAry[] = (string) $v;
}
}
// Set header output.
$output .= implode($delim, $headerAry) . "\n";
// Initialize and clean the field values.
foreach ($data as $value) {
$rowAry = array();
foreach ($value as $key => $val) {
if (!in_array($key, $omit)) {
if (null !== $dt) {
if (strtotime($val) !== false && (stripos($key, 'date') !== false || stripos($key, 'time') !== false)) {
$v = date($dt, strtotime($val)) != '12/31/1969' ? date($dt, strtotime((string) $val)) : '';
} else {
$v = (string) $val;
}
} else {
$v = (string) $val;
}
if (strpos($v, $esc) !== false) {
$v = str_replace($esc, $esc . $esc, $v);
}
if (strpos($v, $delim) !== false) {
$v = $esc . (string) $v . $esc;
}
$rowAry[] = $v;
}
}
// Set field output.
$output .= implode($delim, $rowAry) . "\n";
}
return $output;
}
public function testEncode() { $ary = array(array('Na"me' => '"Test\'s"', 'Num,Ber' => 1, 'Blah' => 3, 'date' => '2012-01-01'), array('Na"me' => 'Test2', 'Num,Ber' => "2,Yes", 'Blah' => 3, 'date' => 'bogusdate')); $c = Csv::encode($ary); $this->assertContains('Na""me,"Num,Ber"', $c); $this->assertContains('Test2,"2,Yes"', $c); $c = Csv::encode($ary, 'Blah'); $this->assertContains('Na""me,"Num,Ber"', $c); $this->assertContains('Test2,"2,Yes"', $c); }