[BUGFIX] CsvUtility method csvToArray does not handle enclosures right
[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 * This cannot be done by str_getcsv, since it's impossible to handle enclosed cells with a line feed in it
26 *
27 * @param string $input The CSV input
28 * @param string $fieldDelimiter The field delimiter
29 * @param string $fieldEnclosure The field enclosure
30 * @param int $maximumColumns The maximum amount of columns
31 * @return array
32 */
33 static public function csvToArray($input, $fieldDelimiter = ',', $fieldEnclosure = '"', $maximumColumns = 0) {
34 $multiArray = array();
35 $maximumCellCount = 0;
36
37 if (($handle = fopen('php://memory', 'r+')) !== FALSE) {
38 fwrite($handle, $input);
39 rewind($handle);
40 while (($cells = fgetcsv($handle, 0, $fieldDelimiter, $fieldEnclosure)) !== FALSE) {
41 $maximumCellCount = max(count($cells), $maximumCellCount);
42 $multiArray[] = $cells;
43 }
44 fclose($handle);
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 }