2 function csv_like_join($array, $quote_all = FALSE) {
6 foreach ($array as $value) {
13 $result .= csv_quote($value);
15 $result .= maybe_csv_quote($value);
22 function csv_quote($string) {
23 return '"' . str_replace($string, '"', '""') . '"';
26 function maybe_csv_quote($string) {
27 if (need_csv_quote($string)) {
28 return csv_quote($string);
34 function need_csv_quote($string) {
35 if (strpos($string, ',') === FALSE
36 && strpos($string, '"') === FALSE
37 && strpos($string, "\r") === FALSE
38 && strpos($string, "\n") === FALSE)
46 function split_csv_line($record) {
49 if (strlen($record) == 0) {
53 if ($record[0] === '"') {
57 while ($start < strlen($record)
58 && ($end = strpos($record, '"', $start)) !== FALSE
59 && $end < strlen($record) - 1
60 && $record[$end +
1] !== ',')
62 if ($record[$end +
1] !== '"') {
63 die("Found characters between double-quoted field and comma.");
66 $first .= substr($record, $start, $end - $start - 1);
70 if ($start < strlen($record) ||
$end === FALSE) {
71 die("Could not find end-quote for double-quoted field");
74 $first .= substr($record, $start, $end - $start - 1);
76 if ($end >= strlen($record) - 1) {
80 /* Assertion: $record[$end + 1] == ',' */
81 $rest = substr($record, $end +
2);
83 $end = strpos($record, ',');
86 return array($record);
89 /* Assertion: $end < strlen($record) */
91 $first = substr($record, 0, $end);
92 $rest = substr($record, $end +
1);
95 $fields = split_csv_line($rest);
96 array_unshift($fields, $first);