2 function csv_like_join($array, $quote_all = false)
7 foreach ($array as $value) {
14 $result .= csv_quote($value);
16 $result .= maybe_csv_quote($value);
23 function csv_quote($string)
25 return '"' . str_replace($string, '"', '""') . '"';
28 function maybe_csv_quote($string)
30 if (need_csv_quote($string)) {
31 return csv_quote($string);
37 function need_csv_quote($string)
39 if (strpos($string, ',') === false
40 && strpos($string, '"') === false
41 && strpos($string, "\r") === false
42 && strpos($string, "\n") === false)
50 function split_csv_line($record)
54 if (strlen($record) == 0) {
58 if ($record[0] === '"') {
62 while ($start < strlen($record)
63 && ($end = strpos($record, '"', $start)) !== false
64 && $end < strlen($record) - 1
65 && $record[$end +
1] !== ',')
67 if ($record[$end +
1] !== '"') {
68 die("Found characters between double-quoted field and comma.");
71 $first .= substr($record, $start, $end - $start - 1);
75 if ($start < strlen($record) ||
$end === false) {
76 die("Could not find end-quote for double-quoted field");
79 $first .= substr($record, $start, $end - $start - 1);
81 if ($end >= strlen($record) - 1) {
85 /* Assertion: $record[$end + 1] == ',' */
86 $rest = substr($record, $end +
2);
88 $end = strpos($record, ',');
91 return array($record);
94 /* Assertion: $end < strlen($record) */
96 $first = substr($record, 0, $end);
97 $rest = substr($record, $end +
1);
100 $fields = split_csv_line($rest);
101 array_unshift($fields, $first);