[BUGFIX] Table wizard: large fields and BR-tags
[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 public static function csvToArray($input, $fieldDelimiter = ',', $fieldEnclosure = '"', $maximumColumns = 0)
34 {
35 $multiArray = array();
36 $maximumCellCount = 0;
37
38 if (($handle = fopen('php://memory', 'r+')) !== false) {
39 fwrite($handle, $input);
40 rewind($handle);
41 while (($cells = fgetcsv($handle, 0, $fieldDelimiter, $fieldEnclosure)) !== false) {
42 $maximumCellCount = max(count($cells), $maximumCellCount);
43 $multiArray[] = preg_replace('|<br */?>|i', LF, $cells);
44 }
45 fclose($handle);
46 }
47
48 if ($maximumColumns > $maximumCellCount) {
49 $maximumCellCount = $maximumColumns;
50 }
51
52 foreach ($multiArray as &$row) {
53 for ($key = 0; $key < $maximumCellCount; $key++) {
54 if (
55 $maximumColumns > 0
56 && $maximumColumns < $maximumCellCount
57 && $key >= $maximumColumns
58 ) {
59 if (isset($row[$key])) {
60 unset($row[$key]);
61 }
62 } elseif (!isset($row[$key])) {
63 $row[$key] = '';
64 }
65 }
66 }
67
68 return $multiArray;
69 }
70 }