We already saw in another article how to load a node by its ID, but now we need to know how to get the values of its fields. It’s very simple — you just need to know that the node object has the get method, which allows us to retrieve these fields (attributes).
It’s important to note that these fields are also objects themselves, each with their own attributes, depending on the field type. You can find out which attributes are available by debugging with Xdebug (recommended) or by printing the variable using Kint (for example).
1echo $node->get('title')->value; // "Lorem Ipsum..."2echo $node->get('created')->value; // 15109488013echo $node->get('body')->value; // "The full body, <strong>with HTML</strong>"4echo $node->get('body')->summary; // "The summary"5// A text field6echo $node->get('field_foo')->value; // "Whatever is in your custom field"7// A file field8echo $node->get('field_image')->target_id; // 432 (The File ID)
Additionally, with PHP you can use magic methods, which means you don’t even need to write get. So the equivalent of the above would look like this:
1echo $node->title->value; // "Lorem Ipsum..."2echo $node->created->value; // 15109488013echo $node->body->value; // "The full body, <strong>with HTML</strong>"4echo $node->body->summary; // "The summary"5echo $node->field_foo->value; // "Whatever is in your custom field"6echo $node->field_image->target_id; // 432