Skip to content

Instantly share code, notes, and snippets.

@opi
Created March 1, 2018 21:45
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save opi/85c1378b051f20773e195bd2a2aa539c to your computer and use it in GitHub Desktop.
Save opi/85c1378b051f20773e195bd2a2aa539c to your computer and use it in GitHub Desktop.
Backdrop import user from csv
<?php
function MYMODULE_import() {
// Path relative to document root
$csv_filepath = backdrop_get_path('module', 'MYMODULE');
$csv_filepath .= '/user_list.csv';
if ($handle = fopen($csv_filepath, 'r') ) {
// Read from CSV
$line_count = 1;
$user_list = array();
while ($line = fgetcsv($handle, 4096)) {
if (!$line_count > 1) { // 1st line is header
$account = array(
'name' => $line[0],
'phone' => $line[1],
'mail' => $line[2],
'some_date' => $line[3], // should be like 2017-12-30 00:00:00
);
$user_list[] = $account;
}
$line_count++;
}
fclose($handle);
// Create users
if (!empty($user_list)) {
foreach($user_list as $account) {
$new_user = new User();
$new_user->name = $account['name'];
$new_user->pass = user_password(20);
$new_user->mail = $account['mail'];
$new_user->init = $account['mail'];
$new_user->status = 1;
$new_user->created = REQUEST_TIME;
$new_user->data = array(
'contact' => FALSE
);
$new_user->roles = array(
'member', // Role machine name
);
$new_user->field_adherent = array(
LANGUAGE_NONE => array(
0 => array(
'value' => 1,
),
),
);
$new_user->field_name = array(
LANGUAGE_NONE => array(
0 => array(
'value' => $account['name'],
),
),
);
$new_user->field_phone = array(
LANGUAGE_NONE => array(
0 => array(
'value' => $account['phone'],
),
),
);
$new_user->field_some_date = array(
LANGUAGE_NONE => array(
0 => array(
'value' => $account['some_date'],
'timezone' => 'Europe/Paris',
'timezone_db' => 'Europe/Paris',
'date_type' => 'datetime'
),
),
);
$new_user->save();
}
}
}
return "import";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment