<?php include __DIR__ . '/scriptinit.php'; $csvFile = 'extension/sqliimport/stubs/example.csv'; $cli->notice('Processing CSV test file ' . $csvFile); $options = new SQLICSVOptions(array('csv_path' => $csvFile, 'enclosure' => '~')); $csvDoc = new SQLICSVDoc($options); $csvDoc->parse(); $rowCount = count($csvDoc->rows); $cli->notice("There are {$rowCount} rows in CSV file"); // Cleant headers, camel case $headers = $csvDoc->rows->getHeaders(); $cli->warning('Cleant headers : ', false); $cli->notice(implode(', ', $headers)); // Raw headers, as provided in CSV file $rawHeaders = $csvDoc->rows->getRawHeaders(); $cli->warning('Raw headers : ', false); $cli->notice(implode(', ', $rawHeaders)); $cli->notice($csvDoc->rows[0]->myFirstField); // array access //var_dump($csvDoc->rows); foreach ($csvDoc->rows as $row) { $cli->notice($row->myFirstField); $cli->notice($row->otherField); $cli->notice($row->andAnotherOne); $cli->notice(); } $peakMemory = number_format(memory_get_peak_usage(), 0, '.', ' '); $cli->notice('Peak memory usage : ' . $peakMemory . ' octets'); $script->shutdown();
/** * Checks if file is in a valid format for $option * Returns true or throws an SQLIImportInvalidFileFormatException * * @param string $option File option alias * @param string $filePath File to validate. Must be a valid local file (fetched from cluster if needed) * @return boolean * @throws SQLIImportInvalidFileFormatException * @throws SQLIImportConfigException if $option is not right */ public function validateFile($option, $filePath) { if ($option !== 'file') { throw new SQLIImportConfigException('"' . $option . '" is not a valid file option. Correct value is "file"'); } $csvOptions = new SQLICSVOptions(array()); //extract headers in temp file to ensure fast csv parsing $f = fopen($filePath, 'r'); $headersLine = fgets($f, $csvOptions->csv_line_length); $headersLine .= fgets($f, $csvOptions->csv_line_length); fclose($f); $tmpFile = tempnam(sys_get_temp_dir(), 'usersimport'); file_put_contents($tmpFile, $headersLine); $csvOptions->csv_path = $tmpFile; $csv = new SQLICSVDoc($csvOptions); $csv->parse(); unlink($tmpFile); $requiredHeaders = array('login', 'password', 'email', 'firstName', 'lastName'); $sentHeaders = $csv->rows->getHeaders(); $diff = array_diff($requiredHeaders, $sentHeaders); if (!empty($diff)) { throw new SQLIImportInvalidFileFormatException(SQLIImportUtils::translate('sqliimport/usershandler', "File must contain the following columns: %required Sent columns are: %sent", '', array('%required' => implode($csvOptions->delimiter, $requiredHeaders), '%sent' => implode($csvOptions->delimiter, $sentHeaders)))); } return true; }