-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathcsv.php
75 lines (56 loc) · 1.38 KB
/
csv.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
<?php
// Great for converting the output of a database query to a CSV file
// http://www.creativyst.com/Doc/Articles/CSV/CSV01.htm
// https://tools.ietf.org/html/rfc4180
/*
TODO:
getCsvFile(): Handle arbitrary streams, not simply return $input
Detect rows longer than the header
Do not escape fields that do not need escaping
Directly handle the results of a PDO statement after execute()
*/
class CsvUtils {
/**
* Return a legal CSV file
*
* @param $input Array of associative arrays
* @return string
*/
private static function getCsvFile($input, $separator=',')
{
$output = '';
$header = TRUE;
foreach ( $input as $row ) {
$output .= getCsvRow($row, $separator, $header);
$header = FALSE;
}
return $output;
}
/**
* Return a legal CSV row with optional header
*
* @param $row
* @param $r
* @param $header
* @return string
*/
private static function getCsvRow($row, $separator=',', $header=FALSE)
{
if ( $header ) {
$pre = implode($separator, array_map(array(__CLASS__, 'escapeCsvField'), array_keys($row))) . "\n";
} else {
$pre = '';
}
return $pre . implode($separator, array_map(array(__CLASS__, 'escapeCsvField'), $row)) . "\n";
}
/**
* Return a legal CSV field
*
* @param $input
* @return string
*/
private static function escapeCsvField($input)
{
return '"' . str_replace('"', '""', $input) . '"';
}
}