本文整理汇总了PHP中SplFileObject::fgetcsv方法的典型用法代码示例。如果您正苦于以下问题:PHP SplFileObject::fgetcsv方法的具体用法?PHP SplFileObject::fgetcsv怎么用?PHP SplFileObject::fgetcsv使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类SplFileObject
的用法示例。
在下文中一共展示了SplFileObject::fgetcsv方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: getColumns
/**
* @return array
*/
public function getColumns()
{
if ($this->columns === null) {
$this->csvFile->fseek(0);
$this->columns = $this->csvFile->fgetcsv();
}
return $this->columns;
}
示例2: getFile
/**
* @return \SplFileObject
*/
protected function getFile()
{
if (!$this->file instanceof \SplFileObject) {
$this->file = $this->fileInfo->openFile();
$this->file->setFlags(\SplFileObject::READ_CSV | \SplFileObject::READ_AHEAD | \SplFileObject::DROP_NEW_LINE);
$this->file->setCsvControl($this->delimiter, $this->enclosure, $this->escape);
if ($this->firstLineIsHeader && !$this->header) {
$this->header = $this->file->fgetcsv();
}
}
return $this->file;
}
示例3: exportedFileOfShouldContain
/**
* @param string $code
* @param PyStringNode $csv
*
* @Then /^exported file of "([^"]*)" should contain:$/
*
* @throws ExpectationException
* @throws \Exception
*/
public function exportedFileOfShouldContain($code, PyStringNode $csv)
{
$config = $this->getFixturesContext()->getJobInstance($code)->getRawConfiguration();
$path = $this->getMainContext()->getSubcontext('job')->getJobInstancePath($code);
if (!is_file($path)) {
throw $this->getMainContext()->createExpectationException(sprintf('File "%s" doesn\'t exist', $path));
}
$delimiter = isset($config['delimiter']) ? $config['delimiter'] : ';';
$enclosure = isset($config['enclosure']) ? $config['enclosure'] : '"';
$escape = isset($config['escape']) ? $config['escape'] : '\\';
$csvFile = new \SplFileObject($path);
$csvFile->setFlags(\SplFileObject::READ_CSV | \SplFileObject::READ_AHEAD | \SplFileObject::SKIP_EMPTY | \SplFileObject::DROP_NEW_LINE);
$csvFile->setCsvControl($delimiter, $enclosure, $escape);
$expectedLines = [];
foreach ($csv->getLines() as $line) {
if (!empty($line)) {
$expectedLines[] = explode($delimiter, str_replace($enclosure, '', $line));
}
}
$actualLines = [];
while ($data = $csvFile->fgetcsv()) {
if (!empty($data)) {
$actualLines[] = array_map(function ($item) use($enclosure) {
return str_replace($enclosure, '', $item);
}, $data);
}
}
$expectedCount = count($expectedLines);
$actualCount = count($actualLines);
assertSame($expectedCount, $actualCount, sprintf('Expecting to see %d rows, found %d', $expectedCount, $actualCount));
if (md5(json_encode($actualLines[0])) !== md5(json_encode($expectedLines[0]))) {
throw new \Exception(sprintf('Header in the file %s does not match expected one: %s', $path, implode(' | ', $actualLines[0])));
}
unset($actualLines[0]);
unset($expectedLines[0]);
foreach ($expectedLines as $expectedLine) {
$originalExpectedLine = $expectedLine;
$found = false;
foreach ($actualLines as $index => $actualLine) {
// Order of columns is not ensured
// Sorting the line values allows to have two identical lines
// with values in different orders
sort($expectedLine);
sort($actualLine);
// Same thing for the rows
// Order of the rows is not reliable
// So we generate a hash for the current line and ensured that
// the generated file contains a line with the same hash
if (md5(json_encode($actualLine)) === md5(json_encode($expectedLine))) {
$found = true;
// Unset line to prevent comparing it twice
unset($actualLines[$index]);
break;
}
}
if (!$found) {
throw new \Exception(sprintf('Could not find a line containing "%s" in %s', implode(' | ', $originalExpectedLine), $path));
}
}
}
示例4: _getCSVLine
/**
* Returns a line form the CSV file and advances the pointer to the next one
*
* @param Model $Model
* @param SplFileObject $handle CSV file handler
* @return array list of attributes fetched from the CSV file
*/
protected function _getCSVLine(Model &$Model, SplFileObject $handle)
{
if ($handle->eof()) {
return false;
}
return $handle->fgetcsv($this->settings[$Model->alias]['delimiter'], $this->settings[$Model->alias]['enclosure']);
}
示例5: submitForm
/**
* {@inheritdoc}
*/
public function submitForm(array &$form, FormStateInterface $form_state)
{
$values = $form_state->getValues();
$file = File::load($values['file'][0]);
// Load File entity.
$read_file = new \SplFileObject($file->url());
// Create file handler.
$lines = 1;
$in_queue = 0;
$queue = \Drupal::queue('eventninja');
// Load queue
while (!$read_file->eof()) {
$data = $read_file->fgetcsv(';');
if ($lines > 1) {
// skip headers
$user = user_load_by_mail($data[1]);
if ($user === false) {
// Verify if user with specified email does not exist.
$queue->createItem($data);
$in_queue++;
} else {
$this->logger('eventninja')->log(RfcLogLevel::NOTICE, 'User {mail} hasn\'t been created.', ['mail' => $data[1]]);
}
}
$lines++;
}
if ($lines > 1) {
drupal_set_message($this->t('@num records was scheduled for import', array('@num' => $in_queue)), 'success');
} else {
drupal_set_message($this->t('File contains only headers'), 'error');
}
}
示例6: readElement
/**
* Reads a single element from the source
* then return a Object instance
*
* @return \StdClass|false object instance
*/
public function readElement()
{
$csv_line_data = $this->spl_file_object->fgetcsv();
if ($csv_line_data) {
$csv_line_data[0] = $this->convertToUtf8($csv_line_data);
// questo controllo è per quando si esporta da excel
if (!$csv_line_data[0]) {
return false;
}
$csv_line = array_combine($this->columns_name, $csv_line_data);
// we cast it to StdClass
return (object) $csv_line;
} else {
return false;
}
}
示例7: parse
/**
* Parses a file of data into a php array.
*
* @param \SplFileObject $file
*
* @return array
*/
public function parse(\SplFileObject $file)
{
$delimiter = $this->options['delimiter'];
$enclosure = $this->options['enclosure'];
$escape = $this->options['escape'];
$header = $file->fgetcsv($delimiter, $enclosure, $escape);
$result = [];
while (!$file->eof()) {
$line = $file->fgetcsv($delimiter, $enclosure, $escape);
// If row is not a blank line.
if (!empty($line[0])) {
$result[] = array_combine($header, $line);
}
}
return $result;
}
示例8: read
/**
* {@inheritdoc}
*/
public function read()
{
if (null === $this->csv) {
if (mime_content_type($this->filePath) === 'application/zip') {
$this->extractZipArchive();
}
$this->csv = new \SplFileObject($this->filePath);
$this->csv->setFlags(\SplFileObject::READ_CSV | \SplFileObject::READ_AHEAD | \SplFileObject::SKIP_EMPTY | \SplFileObject::DROP_NEW_LINE);
$this->csv->setCsvControl($this->delimiter, $this->enclosure, $this->escape);
$this->fieldNames = $this->csv->fgetcsv();
}
$data = $this->csv->fgetcsv();
if (false !== $data) {
if ($data === array(null) || $data === null) {
return null;
}
if ($this->stepExecution) {
$this->stepExecution->incrementSummaryInfo('read');
}
if (count($this->fieldNames) !== count($data)) {
throw new InvalidItemException('pim_base_connector.steps.csv_reader.invalid_item_columns_count', $data, array('%totalColumnsCount%' => count($this->fieldNames), '%itemColumnsCount%' => count($data), '%csvPath%' => $this->csv->getRealPath(), '%lineno%' => $this->csv->key()));
}
$data = array_combine($this->fieldNames, $data);
} else {
throw new \RuntimeException('An error occured while reading the csv.');
}
return $data;
}
示例9: parse
/**
* Parse les pleins et remplit le tableau $pleins.
*
* @param \SplFileObject $file Fichier CSV fourni par MyCars.
*/
public function parse(\SplFileObject $file)
{
// Repository
$vehiculeRepository = $this->em->getRepository('ComptesBundle:Vehicule');
// Configuration du handler
$configuration = $this->configuration['mycars.csv'];
// Tableau de correspondance entre le nom du véhicule dans MyCars et l'objet Vehicule
$vehicules = array();
foreach ($configuration['vehicules'] as $vehiculeLabel => $vehiculeID) {
$vehicules[$vehiculeLabel] = $vehiculeRepository->find($vehiculeID);
}
// Lignes du fichier CSV qui représentent des pleins
$refuels = array();
// Les en-têtes de colonnes
$headers = array();
// Numéros de ligne
$currentLine = 0;
$headersLine = false;
while (($cols = $file->fgetcsv()) !== null) {
// Recherche de la ligne d'en-têtes
if ($cols[0] == "#entity: refuel") {
$headersLine = $currentLine + 1;
}
// Si la ligne d'en-têtes a été trouvée et qu'on l'a dépassée
if ($headersLine !== false && $currentLine > $headersLine) {
// La ligne en cours est un plein
$refuel = array_combine($headers, $cols);
$refuels[] = $refuel;
} elseif ($currentLine == $headersLine) {
$headers = $cols;
}
$currentLine++;
}
foreach ($refuels as $refuel) {
$plein = new Plein();
// Véhicule
$vehiculeName = (string) $refuel['##car_name'];
$vehicule = $vehicules[$vehiculeName];
$plein->setVehicule($vehicule);
// Date
$date = \DateTime::createFromFormat('Y-m-d G:i', (string) $refuel['refuelDate']);
$plein->setDate($date);
// Distance parcourue
$distanceParcourue = (string) $refuel['distance'];
$plein->setDistanceParcourue($distanceParcourue);
// Montant
$montant = (string) $refuel['price'] * (string) $refuel['quantity'];
$plein->setMontant($montant);
// Prix au litre
$prixLitre = (string) $refuel['price'];
$plein->setPrixLitre($prixLitre);
// Quantité
$quantite = (string) $refuel['quantity'];
$plein->setQuantite($quantite);
// Classification
$classification = $this->getClassification($plein);
$this->classify($plein, $classification);
}
}
示例10: __construct
public function __construct($csvFile)
{
$file = new SplFileObject($csvFile);
while (!$file->eof()) {
$csv[] = $file->fgetcsv();
}
$this->File = $csv;
}
示例11: initializeRead
/**
* Initialize read process by extracting zip if needed, setting CSV options
* and settings field names.
*/
protected function initializeRead()
{
if (mime_content_type($this->filePath) === 'application/zip') {
$this->extractZipArchive();
}
$this->csv = new \SplFileObject($this->filePath);
$this->csv->setFlags(\SplFileObject::READ_CSV | \SplFileObject::READ_AHEAD | \SplFileObject::SKIP_EMPTY | \SplFileObject::DROP_NEW_LINE);
$this->csv->setCsvControl($this->delimiter, $this->enclosure, $this->escape);
$this->fieldNames = $this->csv->fgetcsv();
}
示例12: parse
/**
* Parses a file of data into a php array.
*
* @param \SplFileObject $file
*
* @return array
*/
public function parse(\SplFileObject $file)
{
$result = [];
$delimiter = $this->options['delimiter'];
$enclosure = $this->options['enclosure'];
$escape = $this->options['escape'];
while (!$file->eof()) {
$this->formatLine($result, $file->fgetcsv($delimiter, $enclosure, $escape));
}
return $result;
}
示例13: initializeRead
/**
* Initialize read process by extracting zip if needed, setting CSV options
* and settings field names.
*/
protected function initializeRead()
{
// TODO mime_content_type is deprecated, use Symfony\Component\HttpFoundation\File\MimeTypeMimeTypeGuesser?
if ('application/zip' === mime_content_type($this->filePath)) {
$this->extractZipArchive();
}
$this->csv = new \SplFileObject($this->filePath);
$this->csv->setFlags(\SplFileObject::READ_CSV | \SplFileObject::READ_AHEAD | \SplFileObject::SKIP_EMPTY | \SplFileObject::DROP_NEW_LINE);
$this->csv->setCsvControl($this->delimiter, $this->enclosure, $this->escape);
$this->fieldNames = $this->csv->fgetcsv();
}
示例14: parse
/**
* Parse les mouvements et remplit les tableaux de classification du handler.
*
* @param \SplFileObject $file Fichier CSV fourni par le CIC.
*/
public function parse(\SplFileObject $file)
{
// Repository
$compteRepository = $this->em->getRepository('ComptesBundle:Compte');
// Configuration du handler
$configuration = $this->configuration['cic.csv'];
// Le compte bancaire dans lequel importer les mouvements
$compteID = $configuration['compte'];
$compte = $compteRepository->find($compteID);
// Lignes du fichier CSV qui représentent des mouvements
$rows = array();
// Les en-têtes de colonnes
$headers = array('date_operation', 'date_valeur', 'debit', 'credit', 'libelle', 'solde');
// Numéros de ligne
$currentLine = 0;
$headersLine = 0;
while (($cols = $file->fgetcsv(';')) !== null) {
// Si on a dépassé la ligne d'en-têtes
if ($currentLine > $headersLine) {
// Si la date est valide et sans month shifting
$date = \DateTime::createFromFormat('d/m/Y', $cols[0]);
$isValidDate = $date !== false && !array_sum($date->getLastErrors());
// Alors la ligne en cours est un mouvement
if ($isValidDate) {
$row = array_combine($headers, $cols);
$rows[] = $row;
}
}
$currentLine++;
}
foreach ($rows as $row) {
$mouvement = new Mouvement();
// Date
$date = \DateTime::createFromFormat('d/m/Y', (string) $row['date_operation']);
$mouvement->setDate($date);
// Compte
$mouvement->setCompte($compte);
// Montant
$montant = $row['debit'] !== '' ? $row['debit'] : $row['credit'];
$montant = str_replace(',', '.', $montant);
$montant = sprintf('%0.2f', $montant);
$mouvement->setMontant($montant);
// Description
$description = $row['libelle'];
$mouvement->setDescription($description);
// Classification
$classification = $this->getClassification($mouvement);
$this->classify($mouvement, $classification);
}
}
示例15: parseFile
/**
* @param \Closure $callback
*/
protected function parseFile(\Closure $callback)
{
while (!$this->file->eof()) {
if (strlen($this->delim) == 1) {
$data = $this->file->fgetcsv($this->delim, $this->enclosure);
} else {
$data = explode($this->delim, $this->file->fgets());
$data = array_map(function ($row) {
return mb_convert_encoding(trim($row, $this->enclosure), "UTF-8", "Windows-1252,ISO-8859-15");
}, $data);
if ($this->debug) {
break;
}
/*
$enclosure = $this->enclosure;
array_walk($data, function(&$val) use ($enclosure) {
return trim($val, $enclosure);
});
*/
}
$callback($data);
}
}