3v4l.org

run code in 200+ php & hhvm versions
Bugs & Features
<?php function fputcsv2(&$handle, $fields = array(), $delimiter = ',', $enclosure = '"', $escape_char = '\\') { $str = ''; foreach ($fields as $value) { $needQuote = strpos($value, $delimiter) !== false || strpos($value, $enclosure) !== false || strpos($value, "\n") !== false || strpos($value, "\r") !== false || strpos($value, "\t") !== false || strpos($value, ' ') !== false; if ($needQuote) { $str2 = $enclosure; $escaped = 0; $len = strlen($value); for ($i = 0; $i < $len; $i++) { if ($value[$i] == $escape_char) { $escaped = 1; } else if (!$escaped && $value[$i] == $enclosure) { $str2 .= $enclosure; } else { $escaped = 0; } $str2 .= $value[$i]; } $str2 .= $enclosure; $str .= $str2.$delimiter; } else { $str .= $value.$delimiter; } } $str = substr($str,0,-1); $str .= "\n"; return fwrite($handle, $str); } $list = array ( array('aaa,', 'bbb', 'ccc', 'dddd'), array('123', '456', '789'), array('"aaa"', '"bbb"') ); $fp = fopen('/tmp/file.csv', 'w'); foreach ($list as $fields) { fputcsv2($fp, $fields, ',,'); } fclose($fp); echo file_get_contents('/tmp/file.csv');
based on M7Nic
Output for 4.3.0 - 7.2.0
aaa,,,bbb,,ccc,,dddd, 123,,456,,789, """aaa""",,"""bbb""",