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

Filtered HTML

  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <blockquote> <code> <ul> <ol> <li> <dl> <dt> <dd>
  • Lines and paragraphs break automatically.

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.
CAPTCHA
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.