This MODX Snippet parse CSV Data and return it to chunk
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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