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

$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;

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!)


Add new comment