1: <?php
2:
3: class CsvUtil {
4:
5: private static $defaultOptions = array(
6: 'delimiter' => ',',
7: 'enclosure' => '"',
8: 'encoding' => false,
9: );
10:
11: public static function fileToArray($filePath, $options = array()) {
12: return self::contentToArray(file_get_contents($filePath), $options);
13: }
14:
15: public static function fileToArrayWithColumns($filePath,
16: $convertFunction = null) {
17: $lines = self::fileToArray($filePath);
18: $columns = array_shift($lines);
19: if (!$columns) {
20: throw new Exception("File \"$filePath\" has no columns line");
21: }
22: $ret = array();
23: foreach ($lines as $row) {
24: $ret[] = self::_rawRowToAssociativeRow($row, $columns, $convertFunction);
25: }
26: return $ret;
27: }
28:
29: public static function contentToArray($content, $options = array()) {
30: assert(is_array($options), '$options is not a array: ' . var_export($options, true));
31: $options += self::$defaultOptions;
32: if ($options['encoding']) {
33: $content = mb_convert_encoding($content, mb_internal_encoding(), $options['encoding']);
34: }
35: $lines = array();
36: foreach (preg_split ('/\R/', $content) as $k => $sourceLine) {
37: if (trim($sourceLine) == '') {
38: continue;
39: }
40: $lines[] = str_getcsv($sourceLine, $options['delimiter'], $options['enclosure']);
41: }
42: return $lines;
43: }
44:
45: public static function arrayToFile($filePath, $lines) {
46: if (($handle = fopen($filePath, "w")) !== FALSE) {
47: foreach ($lines as $line) {
48: fputcsv($handle, $line);
49: }
50: fclose($handle);
51: } else {
52: throw new Exception("Failed to open file \"$filePath\"");
53: }
54: }
55:
56: private static function _rawRowToAssociativeRow($row, $columns,
57: $convertFunction) {
58: $ret = array();
59: foreach ($columns as $columnIndex => $columnName) {
60: $ret[$columnName] = self::_rowValue($row[$columnIndex], $columnName, $convertFunction);
61: }
62: return $ret;
63: }
64:
65: private static function _rowValue($value, $column, $convertFunction) {
66: return $convertFunction ?
67: call_user_func($convertFunction, $column, $value) :
68: $value;
69: }
70:
71: }
72: