/** * Get a new CSVParser using defined settings. * @return Iterator */ public function getIterator() { if (!file_exists($this->filepath)) { //TODO: throw exception instead? return null; } $header = $this->hasheader ? $this->getFirstRow() : null; $output = array(); $config = new LexerConfig(); $config->setDelimiter($this->delimiter); $config->setEnclosure($this->enclosure); $config->setIgnoreHeaderLine($this->hasheader); $interpreter = new Interpreter(); // Ignore row column count consistency $interpreter->unstrict(); $interpreter->addObserver(function (array $row) use(&$output, $header) { if ($header) { //create new row using headings as keys $newrow = array(); foreach ($header as $k => $heading) { if (isset($row[$k])) { $newrow[$heading] = $row[$k]; } } $row = $newrow; } $output[] = $row; }); $lexer = new Lexer($config); $lexer->parse($this->filepath, $interpreter); return new ArrayIterator($output); }
public function testEnclosure() { $config = new LexerConfig(); $this->assertSame('"', $config->getEnclosure()); $this->assertSame('enc', $config->setEnclosure('enc')->getEnclosure()); }
/** * CSV parser * * @param string $file Path of the file. * @return array Returns the array from csv. * @since 0.1.0 */ public static function csv_parser($csv_file) { if (!is_file($csv_file)) { return new WP_Error('error', 'The CSV file is not found.'); } elseif (!self::is_textfile($csv_file)) { return new WP_Error('error', 'The file is not CSV.'); } $csv = array(); /** * Filter the CSV setting for the csv parser. * * @param array settings for the csv parser. */ $format = apply_filters('acsv_csv_format', array('from_charset' => 'UTF-8', 'to_charset' => 'UTF-8', 'delimiter' => ',', 'enclosure' => '"', 'escape' => '\\')); $config = new LexerConfig(); $config->setFromCharset($format['from_charset']); $config->setToCharset($format['to_charset']); $config->setDelimiter($format['delimiter']); $config->setEnclosure($format['enclosure']); $config->setEscape($format['escape']); $lexer = new Lexer($config); $interpreter = new Interpreter(); $interpreter->unstrict(); $interpreter->addObserver(function (array $row) use(&$csv) { $csv[] = $row; }); $lexer->parse($csv_file, $interpreter); return $csv; }