[FEATURE] Introduce DataProcessors for splitting values
[Packages/TYPO3.CMS.git] / typo3 / sysext / core / Classes / Utility / CsvUtility.php
1 <?php
2 namespace TYPO3\CMS\Core\Utility;
3
4 /*
5 * This file is part of the TYPO3 CMS project.
6 *
7 * It is free software; you can redistribute it and/or modify it under
8 * the terms of the GNU General Public License, either version 2
9 * of the License, or any later version.
10 *
11 * For the full copyright and license information, please read the
12 * LICENSE.txt file that was distributed with this source code.
13 *
14 * The TYPO3 project - inspiring people to share!
15 */
16
17 /**
18 * Class with helper functions for CSV handling
19 */
20 class CsvUtility {
21
22 /**
23 * Convert a string, formatted as CSV, into an multidimensional array
24 *
25 * @param string $input The CSV input
26 * @param string $fieldDelimiter The field delimiter
27 * @param string $fieldEnclosure The field enclosure
28 * @param string $rowDelimiter The row delimiter
29 * @param int $maximumColumns The maximum amount of columns
30 * @return array
31 */
32 static public function csvToArray($input, $fieldDelimiter = ',', $fieldEnclosure = '"', $rowDelimiter = LF, $maximumColumns = 0) {
33 $multiArray = array();
34 $maximumCellCount = 0;
35
36 // explode() would not work with enclosed newlines
37 $rows = str_getcsv($input, $rowDelimiter);
38
39 foreach ($rows as $row) {
40 $cells = str_getcsv($row, $fieldDelimiter, $fieldEnclosure);
41
42 $maximumCellCount = max(count($cells), $maximumCellCount);
43
44 $multiArray[] = $cells;
45 }
46
47 if ($maximumColumns > $maximumCellCount) {
48 $maximumCellCount = $maximumColumns;
49 }
50
51 foreach ($multiArray as &$row) {
52 for ($key = 0; $key < $maximumCellCount; $key++) {
53 if (
54 $maximumColumns > 0
55 && $maximumColumns < $maximumCellCount
56 && $key >= $maximumColumns
57 ) {
58 if (isset($row[$key])) {
59 unset($row[$key]);
60 }
61 } elseif (!isset($row[$key])) {
62 $row[$key] = '';
63 }
64 }
65 }
66
67 return $multiArray;
68 }
69 }