Skip to content

Instantly share code, notes, and snippets.

@jenswittmann
Created February 18, 2021 10:37
Show Gist options
  • Save jenswittmann/f344ddf39fe0d643b0bd1fdf3e7d9d2f to your computer and use it in GitHub Desktop.
Save jenswittmann/f344ddf39fe0d643b0bd1fdf3e7d9d2f to your computer and use it in GitHub Desktop.
This MODX Snippet parse CSV Data and return it to chunk
<?php
/**
* csvParse
*
* DESCRIPTION
*
* This Snippet parse CSV Data and return it to chunk
*
* PROPERTIES:
*
* &file required
* &delimiter
* &tpl required
* &placeholderPrefix
* &offset int
* &limit int
*
* USAGE:
*
* [[csvParse?
* &file=`file.csv`
* &tpl=`row` ]]
*
*/
# vars
$file = $modx->getOption('file', $scriptProperties, false);
$delimiter = $modx->getOption('delimiter', $scriptProperties, ';');
$tpl = $modx->getOption('tpl', $scriptProperties, $inlineTplPrefix . ' ');
$placeholderPrefix = $modx->getOption(
'placeholderPrefix',
$scriptProperties,
'cell_'
);
$offset = $modx->getOption('offset', $scriptProperties, 0);
$limit = $modx->getOption('limit', $scriptProperties, 100);
$pdo = $modx->getService('pdoFetch');
$idx = 0;
$output = [];
# read csv
if (($handle = fopen(MODX_BASE_PATH . $file, 'r')) !== false) {
while (($data = fgetcsv($handle, 1000, $delimiter)) !== false) {
if ($idx >= $offset && $idx <= $limit) {
foreach ($data as $i => $cell) {
if (!empty($cell)) {
$placeholders[$placeholderPrefix . $i] = $cell;
}
}
$output[] = $modx->getChunk(
$tpl,
array_merge($placeholders, [
'idx' => $idx,
])
);
}
$idx++;
}
fclose($handle);
}
return implode('', $output);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment