Many websites must read csv files, to import customer data, to read some custom settings, etc…
We will expand this class later to set the csv options from an xml config file or a database, but for now see examples below.
To read data from a csv file, we need a csv file first. We store the below data into the file “example.csv”.
1 2 3 |
HeadFoo,HeadBar,HeadIgnoreMe,HeadQuz "somefoo here","some bar here","do not show me",42 "more foo","more bar","more to ignore",88 |
The standard csv options are:
1 2 3 4 5 |
$length = 0 $delimiter = "," $enclosure = '"' $escape = "\\" $headline = true |
Now we can read the data from the “example.csv”. Here are two examples to get the csv data from the file:
1. Foreach
1 2 3 4 |
<?php $file = "example.csv"; $csvArray = array(); $csvIterator = new CsvIterator($file); foreach ($csvIterator as $key => $value) { $csvArray[$key] = $value; } var_dump($csvArray); |
Here is the ouput from the code above:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
array(2) { [1]=> array(4) { [0]=> string(12) "somefoo here" [1]=> string(13) "some bar here" [2]=> string(14) "do not show me" [3]=> string(2) "42" } [2]=> array(4) { [0]=> string(8) "more foo" [1]=> string(8) "more bar" [2]=> string(14) "more to ignore" [3]=> string(2) "88" } } |
2. Get combined array
1 2 |
<?php $file = "example.csv"; $structure = array('FOO', 'BAR', 'XXXX', 'QUZ'); $csvIterator = new CsvIterator($file); $csvIterator->setStructure($structure); var_dump($csvIterator->getCombinedData()); |
The output:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
array(2) { [1]=> array(3) { ["FOO"]=> string(12) "somefoo here" ["BAR"]=> string(13) "some bar here" ["QUZ"]=> string(2) "42" } [2]=> array(3) { ["FOO"]=> string(8) "more foo" ["BAR"]=> string(8) "more bar" ["QUZ"]=> string(2) "88" } } |
PROJECT_ROOT/vendor/PHPluz/CsvIterator.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 |
<?php namespace PHPluz; use Iterator; use Monolog\Logger; /** * CsvIterator * * Simple class to read csv files * * Example standard: * $file = "example.csv"; * $csvArray = array(); * $csvIterator = new CsvIterator($file); * foreach ($csvIterator as $key => $value) { * $csvArray[$key] = $value; * } * var_dump($csvArray); * Example with array combine: * $file = "example.csv"; * $structure = array('FOO', 'BAR', 'XXXX', 'QUZ'); * $csvIterator = new CsvIterator($file); * $csvIterator->setStructure($structure); * var_dump($csvIterator->getCombinedData()); * * @package PHPluz * * @author Janis Jekabsons <php@pluz.de> * @copyright 2016 Janis Jekabsons * @license https://opensource.org/licenses/MIT (MIT) * @version 1.0 */ class CsvIterator implements Iterator { /** @var int $length */ private $length; /** @var string $delimiter */ private $delimiter; /** @var string $enclosure */ private $enclosure; /** @var string $escape */ private $escape; /** @var bool $headline */ private $headline; /** @var \Monolog\Logger $logger */ private $logger; /** @var array $structure */ private $structure; /** @var resource $filePointer fopen handler */ protected $filePointer; /** @var int $key Current row in file */ protected $key = 0; /** @var mixed $current Data row */ protected $current; /** * CsvFileIterator constructor. * Initialize variables, checks file exist and permission * and opens the file. * * @param string $file Full path to file */ public function __construct($file) { $this->logger = new Logger("CsvIterator"); $this->logger->pushHandler(Functions::getLoggerStreamHandler()); // remove BOM when exists if (! Functions::removeBOM($file, $this->logger)) { // throw exception or do what ever you want ;) } $this->setStandardCsvOptions(); // open file $this->filePointer = fopen($file, 'r'); // get file info $fileInfo = pathinfo($file); $this->logger->addDebug("The file ({$fileInfo['basename']}) was opened."); } /** * Destructor to close file */ public function __destruct() { fclose($this->filePointer); $this->logger->addDebug("The file was closed."); } /** * Return the current element * * @link http://php.net/manual/en/iterator.current.php * @since 5.0.0 * * @return mixed Can return any type. */ public function current() { if ($this->checkHeadline()) { $this->next(); } $this->logger->addDebug("Returns the current element."); return $this->current; } /** * Move forward to next element * * @link http://php.net/manual/en/iterator.next.php * @since 5.0.0 * * @return void Any returned value is ignored. */ public function next() { $this->logger->addDebug("Move forward to next element."); $this->current = fgetcsv($this->filePointer, $this->length, $this->delimiter, $this->enclosure, $this->escape); $this->key++; } /** * Return the key of the current element * * @link http://php.net/manual/en/iterator.key.php * @since 5.0.0 * * @return mixed scalar on success, or null on failure. */ public function key() { $this->logger->addDebug("Returns the key of the current element."); return $this->key; } /** * Checks if current position is valid * * @link http://php.net/manual/en/iterator.valid.php * @since 5.0.0 * * @return bool The return value will be casted to bool and then evaluated. * Returns true on success or false on failure. */ public function valid() { $this->logger->addDebug("Checks if the current position is allowed."); return ! feof($this->filePointer); } /** * Rewind the Iterator to the first element * * @link http://php.net/manual/en/iterator.rewind.php * @since 5.0.0 * * @return void Any returned value is ignored. */ public function rewind() { $this->logger->addDebug("Rewind the Iterator to the first element."); rewind($this->filePointer); $this->current = fgetcsv($this->filePointer, $this->length, $this->delimiter, $this->enclosure, $this->escape); $this->key = 0; } /** * Function setCsvOptions * * When no parameters given then standard values are assigned. * * Possible options: * int $length = 0 * string $delimiter = "," * string $enclosure = '"' * string $escape = "\\" * bool $headline = true * * Example: * $file = "example.csv"; * $csvIterator = new CsvIterator($file); * $csvIterator->setCsvOptions(array( * 'length' => 1024, * 'delimiter' => ';', * 'enclosure' => '"', * 'escape' => '\\', * 'headline' => false * )); */ public function setCsvOptions() { $this->logger->addDebug("Set custom csv options:"); if (func_num_args() === 1) { $options = func_get_args(); if (! empty($options[0]['length'])) { $this->length = (int)$options[0]['length']; $this->logger->addDebug("length = {$this->length}"); } if (! empty($options[0]['delimiter'])) { $this->delimiter = $options[0]['delimiter']; $this->logger->addDebug("delimiter = {$this->delimiter}"); } if (! empty($options[0]['enclosure'])) { $this->enclosure = $options[0]['enclosure']; $this->logger->addDebug("enclosure = {$this->enclosure}"); } if (! empty($options[0]['escape'])) { $this->escape = $options[0]['escape']; $this->logger->addDebug("escape = {$this->escape}"); } if (! empty($options[0]['headline'])) { $this->headline = (bool)$options[0]['headline']; $this->logger->addDebug("headline = {$this->headline}"); } } } /** * Function setStandardCsvOptions */ private function setStandardCsvOptions() { $this->logger->addDebug("Set standard csv options:"); $this->length = 0; $this->logger->addDebug("length = {$this->length}"); $this->delimiter = ","; $this->logger->addDebug("delimiter = {$this->delimiter}"); $this->enclosure = '"'; $this->logger->addDebug("enclosure = {$this->enclosure}"); $this->escape = "\\"; $this->logger->addDebug("escape = {$this->escape}"); $this->headline = true; $this->logger->addDebug("headline = {$this->headline}"); } /** * Set a the structure for the csv. Needed when you want to combine * the structure with the csv values. * * @param array $structure Structure of the csv data */ public function setStructure(array $structure) { $this->logger->addDebug("Set csv structure."); $this->structure = $structure; } /** * Function getCombinedCsvData * Combines specified structure (key) and data structure (value) * * you can ignore columns when you set them to 'XXXX' in the structure * * Example: * Specified: array('FOO', 'BAR', 'XXXX', 'QUZ') * Data: array('some foo', 'some bar', 'whatever', 'some quz') * Combined: array('FOO' => 'some foo', 'BAR' => 'some bar', 'QUZ' => 'some quz') * * @param bool $removeEmpty When true empty values are removed from the array * * @return array Combined array */ public function getCombinedData($removeEmpty = false) { $response = array(); $this->logger->addDebug("Start combine data and structure."); foreach ($this as $row => $data) { if ($this->checkHeadline()) { continue; } $countCsv = count($this->structure); $countData = count($data); if ($countCsv !== $countData) { $this->logger->addWarning("Structure at row ({$this->key}) not equal specified structure, row will be skipped. Expected ({$countCsv}) got ({$countData}) elements."); continue; } $response[$this->key] = array_combine($this->structure, $data); $removeEmpty ? $response[$this->key] = Functions::removeEmpty($response[$this->key]) : null; unset($response[$this->key]['XXXX']); } $this->logger->addDebug("Finished combine data and structure."); return $response; } /** * When headline is set to true and we are at the first line (headline) * then return true so you can skip the headline. * * @return bool */ private function checkHeadline() { if ($this->key === 0 && $this->headline === true) { $this->logger->addDebug("Headline skipped."); return true; } return false; } } |