Adding tags to nodes programmatically?

Hi everybody,

I have an existing (imported) list of tags in the taxonomy vocabulary tags. Now I need to attach the tags to new nodes programmatically. Creating the new nodes isn’t a problem, I found some pretty straightforward code for that. What I didn’t find is a way how to attach tags by id to the imported node. I tried this code snippet, but it doesn’t work as it is.

//id of your taxonomy term
$tid = 1;

//add term to a node field

$node->tags[$node->language][0]['tid'] = $tid;

Is there a way to add the tags before saving the node?

Thankful for any help!

Drupal version: