Creating a node with Drupal 8

Creating a node with PHP in Drupal 8 is easy and not much different than in Drupal 7. The following is how to create a base node. I've also included how to fill in a few of the typical fields, you'll probably want to add more or use different ones. Lastly, I've updated the path alias.

    // create base node
    $node = Node::create([
      'type' => $type,
      'title' => $title,
      'langcode' => 'en', // or your language
      'uid' => 2,
    ]);
    // basic body field
    $node->body->setValue([
      'value' => $body,
      'format' => 'full_html',
    ]);
    // term field
    $node->field_taxonomy[] = array('target_id' => $term->id());
    // save new node
    $node->save();
    // save path
    $path = array_search('path', $keys);
    \Drupal::service('path.alias_storage')->save('/node/' . $node->id(), '/' . $path, 'en');
Category: 
Tags: