Adding files to entities programmatically

I recently had a need to migrate a load of files from one site to another, and the use of something like Feeds or Migrate wasn't appropriate.  I found the following suggestion at http://drupal.stackexchange.com/questions/23890/import-files-into-a-file-field-in-drupal-7:

$entity = entity_load($id);
$data = file_get_contents($localpath);
$destination = file_create_filename(basename($localpath), file_default_scheme() . '://yourdir/' );
$file = file_save_data($data, $destination);
$entity->field_attachment[LANGUAGE_NONE][] = (array)$file;
$entity->save();

I haven't tried it yet, but it looks about right...but the name of the field ('field_attachment') may, of course, be different.

(Expect an edit to this post if I find it doesn't work!)

Tags: 

Add new comment