Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Export Drupal Nodes to CSV with EntityFieldQuery and PHP 5
<?php
function om_exporter_drush_command() {
$items['export-newest'] = array(
'description' => 'Export Newest Content to CSV',
'aliases' => ['ex-new'],
'callback' => 'om_export_newest',
'arguments' => [
'date' => '',
]
);
return $items;
}
function om_export_newest($date_arg) {
$tz = variable_get('date_default_timezone', 'UTC');
$tz = new \DateTimeZone($tz);
// First validate date, we assume $date_arg
// is astring that can be parsed by \DateTime
// so you have the flexibility to pass
// in '-1 months' or '28 days ago'
try {
$since = new \DateTime($date_arg, $tz);
} catch (\Exception $ex) {
watchdog('export-newest',
'Could not parse specified date:' . $ex->getMessage(),
null, WATCHDOG_CRITICAL);
return;
}
// we will use SPL to send our data to STDOUT formatted as CSV
$fout = new \SplFileObject("php://stdout");
// write our headers
$fout->fputcsv([
'nid', 'type', 'title', 'date_created', 'path_alias'
]);
// use a generator to loop through nodes
foreach (nodes_generator($since) as $node) {
$fout->fputcsv([
$node->nid,
$node->type,
$node->title,
$node->created,
url('node/' . $node->nid)
]);
}
}
function nodes_generator(\DateTime $created) {
static $count; // prevent infinite loops
// query for nodes newer than the specified date
$query = $query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'node')
->addMetaData('account', user_load(1)) // Run the query as user 1
->propertyCondition('created', $created->format('U'), '>')
->propertyOrderBy('created', 'ASC');
$result = $query->execute();
if (!empty($result)) {
foreach ($result['node'] as $nid => $row) {
$count++;
// TRUE will reset static cache to keep memory usage low
$node = node_load($row->nid, null, TRUE);
if ($count < 100000) {
yield $node;
}
}
}
return;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.