-
-
Save Burick/871eb9c762f4be1e1109d963f1720467 to your computer and use it in GitHub Desktop.
Example export script to turn MODX Resources into CSV entries for importing in another site.
This file contains hidden or 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 | |
// Only run this via SSH | |
if (PHP_SAPI !== 'cli') return; | |
// Sometimes helpful if processing lots of Resources | |
ini_set('memory_limit', '2048M'); | |
// Init @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'); | |
// Options | |
$template = 1; | |
$resClass = 'modDocument'; | |
$tvnames = array_flip(array('someTV', 'anotherTV', 'thirdTV')); | |
$filename = 'export.csv'; | |
// Query Resources | |
$c = $modx->newQuery('modResource'); | |
$c->where(array( | |
'template' => $template, | |
'class_key' => $resClass, | |
)); | |
$resources = $modx->getCollection('modResource', $c); | |
// Create a "template" Resource | |
$template = $modx->newObject($resClass); | |
$template = $template->toArray(); | |
$idx = 0; | |
// Open a file handle | |
$file = fopen($filename, 'w'); | |
foreach ($resources as $res) { | |
// get resource fields | |
$id = $res->get('id'); | |
$fields = $res->toArray(); | |
// merge in tvnames | |
$fields = array_merge($template, $fields, $tvnames); | |
// add idx for reference | |
$fields['idx'] = $idx; | |
// get tvs from resource | |
$tvs = $res->getMany('TemplateVars'); | |
foreach ($tvs as $tv) { | |
$tvname = $tv->get('name'); | |
// if the tv isn't in our list, skip it | |
if (!isset($fields[$tvname])) continue; | |
// if you want the raw value you can do this | |
//$rawValue = $tv->getValue($id); | |
$processedValue = $tv->renderOutput($id); | |
// set the value | |
$fields[$tvname] = $processedValue; | |
} | |
// first column of the csv should have headers | |
if ($idx === 0) { | |
$columns = array_keys($fields); | |
fputcsv($file, $columns); | |
} | |
// write the row | |
fputcsv($file, $fields); | |
$idx++; | |
} | |
// close file handler | |
if (!fclose($file)) echo 'problem closing file'; | |
exit(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment