2 function csv_like_join($array, $quote_all = false)
7 foreach ($array as $value) {
15 $result .= csv_quote($value);
17 $result .= maybe_csv_quote($value);
24 function csv_quote($string)
26 return '"' . str_replace($string, '"', '""') . '"';
29 function maybe_csv_quote($string)
31 if (need_csv_quote($string)) {
32 return csv_quote($string);
38 function need_csv_quote($string)
40 if (strpos($string, ',') === false
41 && strpos($string, '"') === false
42 && strpos($string, "\r") === false
43 && 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] !== ',') {
66 if ($record[$end +
1] !== '"') {
67 die("Found characters between double-quoted field and comma.");
70 $first .= substr($record, $start, $end - $start - 1);
74 if ($start < strlen($record) ||
$end === false) {
75 die("Could not find end-quote for double-quoted field");
78 $first .= substr($record, $start, $end - $start - 1);
80 if ($end >= strlen($record) - 1) {
84 /* Assertion: $record[$end + 1] == ',' */
85 $rest = substr($record, $end +
2);
87 $end = strpos($record, ',');
90 return array($record);
93 /* Assertion: $end < strlen($record) */
95 $first = substr($record, 0, $end);
96 $rest = substr($record, $end +
1);
99 $fields = split_csv_line($rest);
100 array_unshift($fields, $first);