Magento 2 Documentation  2.3
Documentation for Magento 2 CMS v2.3 (December 2018)
Csv.php
Go to the documentation of this file.
1 <?php
8 
10 
16 class Csv
17 {
21  protected $_lineLength = 0;
22 
26  protected $_delimiter = ',';
27 
31  protected $_enclosure = '"';
32 
36  protected $file;
37 
43  public function __construct(File $file)
44  {
45  $this->file = $file;
46  }
47 
54  public function setLineLength($length)
55  {
56  $this->_lineLength = $length;
57  return $this;
58  }
59 
66  public function setDelimiter($delimiter)
67  {
68  $this->_delimiter = $delimiter;
69  return $this;
70  }
71 
78  public function setEnclosure($enclosure)
79  {
80  $this->_enclosure = $enclosure;
81  return $this;
82  }
83 
91  public function getData($file)
92  {
93  $data = [];
94  if (!file_exists($file)) {
95  throw new \Exception('File "' . $file . '" does not exist');
96  }
97 
98  $fh = fopen($file, 'r');
99  while ($rowData = fgetcsv($fh, $this->_lineLength, $this->_delimiter, $this->_enclosure)) {
100  $data[] = $rowData;
101  }
102  fclose($fh);
103  return $data;
104  }
105 
114  public function getDataPairs($file, $keyIndex = 0, $valueIndex = 1)
115  {
116  $data = [];
117  $csvData = $this->getData($file);
118  foreach ($csvData as $rowData) {
119  if (isset($rowData[$keyIndex])) {
120  $data[$rowData[$keyIndex]] = isset($rowData[$valueIndex]) ? $rowData[$valueIndex] : null;
121  }
122  }
123  return $data;
124  }
125 
136  public function saveData($file, $data)
137  {
138  return $this->appendData($file, $data, 'w');
139  }
140 
152  public function appendData($file, $data, $mode = 'w')
153  {
154  $fileHandler = fopen($file, $mode);
155  foreach ($data as $dataRow) {
156  $this->file->filePutCsv($fileHandler, $dataRow, $this->_delimiter, $this->_enclosure);
157  }
158  fclose($fileHandler);
159 
160  return $this;
161  }
162 }
__construct(File $file)
Definition: Csv.php:43
setDelimiter($delimiter)
Definition: Csv.php:66
saveData($file, $data)
Definition: Csv.php:136
setLineLength($length)
Definition: Csv.php:54
if($exist=($block->getProductCollection() && $block->getProductCollection() ->getSize())) $mode
Definition: grid.phtml:15
setEnclosure($enclosure)
Definition: Csv.php:78
getDataPairs($file, $keyIndex=0, $valueIndex=1)
Definition: Csv.php:114
appendData($file, $data, $mode='w')
Definition: Csv.php:152