You are here

public function FeedsCSVParser::parse in Feeds 7.2

Same name and namespace in other branches
  1. 6 plugins/FeedsCSVParser.inc \FeedsCSVParser::parse()
  2. 7 plugins/FeedsCSVParser.inc \FeedsCSVParser::parse()

Implements FeedsParser::parse().

Overrides FeedsParser::parse

File

plugins/FeedsCSVParser.inc, line 16
Contains the FeedsCSVParser class.

Class

FeedsCSVParser
Parses a given file as a CSV file.

Code

public function parse(FeedsSource $source, FeedsFetcherResult $fetcher_result) {
  $source_config = $source
    ->getConfigFor($this);
  $state = $source
    ->state(FEEDS_PARSE);

  // Load and configure parser.
  feeds_include_library('ParserCSV.inc', 'ParserCSV');
  $parser = new ParserCSV();
  $delimiter = $this
    ->getDelimiterChar($source_config);
  $parser
    ->setDelimiter($delimiter);
  if (isset($source_config['encoding'])) {

    // Encoding can only be set when the mbstring extension is loaded.
    $parser
      ->setEncoding($source_config['encoding']);
  }
  $iterator = new ParserCSVIterator($fetcher_result
    ->getFilePath());
  if (empty($source_config['no_headers'])) {

    // Get first line and use it for column names, convert them to lower case.
    $header = $this
      ->parseHeader($parser, $iterator);
    if (!$header) {
      drupal_set_message(t('The CSV file is empty.'), 'warning', FALSE);
      return new FeedsParserResult();
    }
    $parser
      ->setColumnNames($header);
  }

  // Determine section to parse, parse.
  $start = $state->pointer ? $state->pointer : $parser
    ->lastLinePos();
  $limit = $source->importer
    ->getLimit();
  $rows = $this
    ->parseItems($parser, $iterator, $start, $limit);

  // Report progress.
  $state->total = filesize($fetcher_result
    ->getFilePath());
  $state->pointer = $parser
    ->lastLinePos();
  $progress = $parser
    ->lastLinePos() ? $parser
    ->lastLinePos() : $state->total;
  $state
    ->progress($state->total, $progress);

  // Create a result object and return it.
  return new FeedsParserResult($rows, $source->feed_nid);
}