Skip to content

Instantly share code, notes, and snippets.

@juampynr
Created July 17, 2020 16:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save juampynr/184ef4e55f88aedea755cca62be9e467 to your computer and use it in GitHub Desktop.
Save juampynr/184ef4e55f88aedea755cca62be9e467 to your computer and use it in GitHub Desktop.
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