Skip to content

Instantly share code, notes, and snippets.

@sepiariver
Last active May 31, 2022 21:03
Show Gist options
  • Save sepiariver/6df566e8742a9b6ecfccea6b5a9a6f1f to your computer and use it in GitHub Desktop.
Save sepiariver/6df566e8742a9b6ecfccea6b5a9a6f1f to your computer and use it in GitHub Desktop.
Consumes CSV as output by the sample_csv_export.php script
<?php
// Only ssh users can execute
if (PHP_SAPI !== 'cli') return;
// Comes in handy sometimes
ini_set('memory_limit', '2048M');
// Instantiate MODX
@include(dirname(__FILE__) . '/config.core.php');
if (!defined('MODX_CORE_PATH')) define('MODX_CORE_PATH', dirname(__FILE__) . '/core/');
include_once (MODX_CORE_PATH . "model/modx/modx.class.php");
$modx= new modX();
$modx->initialize('web');
// Set the filename for CSV import
$filename = 'export.csv';
// Open file handle
$file = fopen($filename, 'r');
// prep for iteration
$fields = array();
$idx = 0;
if ($file) {
while (($row = fgetcsv($file)) !== false) {
// First row
if (empty($fields)) {
// Store field names
$fields = $row;
// This just has the headers so we don't do anything else
continue;
}
$array = array();
// iterate through row cells
foreach ($row as $k => $value) {
// Use element from $fields with same index for array key
$array[$fields[$k]] = $value;
}
// Special handling of properties
$props = $modx->fromJSON($array['properties']);
// This can be useful to store data from source site
$props['legacy_import'] = $modx->toJSON($array);
$array['properties'] = $modx->toJSON($props);
// You probably want to override some values on import
/*
$array['parent'] = 1;
$array['template'] = 1;
$array['show_in_tree'] = 1;
$array['hidemenu'] = 1;
$array['uri_override'] = 1;
unset($array['id'], $array['class_key']);
*/
// Create the Resource and save it
$res = $modx->newObject('modResource');
$res->fromArray($array);
$res->save();
$idx++;
}
if (!feof($file)) {
echo "Error: unexpected fgets() fail\n";
}
fclose($file);
}
echo $idx . ' resources created.' . PHP_EOL;
exit();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment