CSVUtil.php
1 <?php
2 /**
3  * wCMF - wemove Content Management Framework
4  * Copyright (C) 2005-2015 wemove digital solutions GmbH
5  *
6  * Licensed under the terms of the MIT License.
7  *
8  * See the LICENSE file distributed with this work for
9  * additional information.
10  */
11 namespace wcmf\lib\util;
12 
13 /**
14  * CSVUtil provides basic support for csv file functionality.
15  * The first line of a csv file is supposed to hold the field names.
16  *
17  * @author ingo herwig <ingo@wemove.com>
18  */
19 class CSVUtil {
20 
21  var $_fields = array();
22 
23  /**
24  * Read a CSV file into an array
25  * @param $filename The name of the CSV file
26  * @param $separator The field separator used in the CSV file (e.g. \\t)
27  * @param $fielddelimiter The field delimiter used in the CSV file (e.g. ")
28  * @return An assoziative array with keys 'fields', 'values' where
29  * values is an array of arrays holding the values
30  */
31  public static function readCSVFile($filename, $separator, $fielddelimiter) {
32  $result = array();
33  $csv = fopen($filename, 'r');
34 
35  // get field definitions
36  $this->_fields = self::getValues(fgets($csv, 4096), $separator, $fielddelimiter);
37  $result['fields'] = $this->_fields;
38  $result['values'] = array();
39 
40  // get values
41  while (!feof ($csv)) {
42  $line = fgets($csv, 4096);
43  if (strlen($line) > 0) {
44  $values = self::getValues($line, $separator, $fielddelimiter);
45  $result['values'][] = $values;
46  }
47  }
48 
49  fclose ($csv);
50  return $result;
51  }
52 
53  /**
54  * Get the values of of field from a line
55  * @param $line The line (represented as array returned from readCSVFile)
56  * @param $fieldName The name of the field
57  * @return The value or false if not existing
58  */
59  private static function getFieldValue($line, $fieldName) {
60  if (in_array($fieldName, $this->_fields)) {
61  return $line[array_search($fieldName, $this->_fields)];
62  }
63  else {
64  return false;
65  }
66  }
67 
68  /**
69  * Get the values of of line
70  * @param $line The line to split
71  * @param $separator The field separator used in the CSV file (e.g. \\t)
72  * @param $fielddelimiter The field delimiter used in the CSV file (e.g. ")
73  * @return An array of values
74  */
75  private static function getValues($line, $separator, $fielddelimiter) {
76  $line = trim($line);
77  $values = preg_split("/".$separator."/", $line);
78 
79  // strip fielddelimiter from values
80  if (strlen($fielddelimiter) > 0) {
81  for($i=0; $i<sizeof($values); $i++) {
82  $values[$i] = trim($values[$i], $fielddelimiter);
83  }
84  }
85  return $values;
86  }
87 }
88 ?>
CSVUtil provides basic support for csv file functionality.
Definition: CSVUtil.php:19
Utility classes.
Definition: namespaces.php:97
static readCSVFile($filename, $separator, $fielddelimiter)
Read a CSV file into an array.
Definition: CSVUtil.php:31