Skip to content

Instantly share code, notes, and snippets.

@lxbarth
Created November 1, 2010 14:11
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save lxbarth/658222 to your computer and use it in GitHub Desktop.
Save lxbarth/658222 to your computer and use it in GitHub Desktop.
Feeds CSV parser splitting cells by a custom delimiter.
<?php
define('MULTI_VALUE_CUSTOM_DELIMITER', '\#');
/**
* Extends FeedsCSVParser to explode row cells by a custom delimiter.
*
* Cells that start with \# will be exploded by the delimiter \#.
*
* So a cell that reads:
*
* \#one\#two\#three
*
* will be exploded into an array with the values
*
* 'one'
* 'two'
* 'three'
*/
class MultiValueCSVParser extends FeedsCSVParser {
/**
* Parse all of the items from the CSV.
*/
protected function parseItems(ParserCSV $parser, ParserCSVIterator $iterator, $start = 0, $limit = 0) {
$rows = parent::parseItems($parser, $iterator, $start, $limit);
foreach ($rows as &$row) {
foreach ($row as &$cell) {
if ($cell && is_string($cell) && strpos($cell, '\#') === 0) {
$cell = substr($cell, 2);
$cell = explode(MULTI_VALUE_CUSTOM_DELIMITER, $cell);
$cell = count($cell) == 1 ? array_shift($cell) : $cell;
}
}
}
return $rows;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment