Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Drupal 7: script to extract all fields
<?php
/**
* Drupal 7 field extract script.
*
* Extracts all fields into a csv file so it can be open with Google Spreadsheet, LibreOffice, or Excel.
*
* Usage:
* 1. Save this file to the docroot.
* 2. run drush php-script exctract_fields.php
* 3. Find the resulting file at the docroot as fields.csv
*/
// Run query to fetch all field instances plus their field bases.
$result = db_query('select fci.entity_type, fci.bundle, fci.field_name, fci.data, fc.type, fc.module
from {field_config_instance} fci
inner join {field_config} fc on fc.id = fci.field_id
order by fci.entity_type ASC, fci.bundle ASC, fci.field_name ASC');
// Build an array with the data.
$csv_data = [];
$csv_data[] = ['entity_type', 'bundle', 'field_name', 'label', 'type', 'module'];
foreach ($result as $record) {
// The label is within the serialized data. Extract it.
$data = unserialize($record->data);
$csv_data[] = [
$record->entity_type,
$record->bundle,
$record->field_name,
!empty($data['label']) ? $data['label'] : '',
$record->type,
$record->module,
];
}
// Create a csv file with the data.
$fp = fopen('fields.csv', 'w');
foreach ($csv_data as $row) {
fputcsv($fp, $row);
}
fclose($fp);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment