How to save Matrix data programmatically in Craft 3 How can you programmatically save an entry that has a Matrix field in Craft 3?

(Something like this gist for Craft 2)
Saving Matrix fields programmatically got a lot easier in Craft 3 thanks to all the content refactoring.

use craft\elements\Entry;
use craft\elements\MatrixBlock;

// Figure out the section &amp; entry type
$section = Craft::$app-&gt;sections-&gt;getSectionByHandle('news');
$entryTypes = $section-&gt;getEntryTypes();
$entryType = reset($entryTypes);

// Create an entry
$entry = new Entry([
    'sectionId' =&gt; $section-&gt;id,
    'typeId' =&gt; $entryType-&gt;id,
    'fieldLayoutId' =&gt; $entryType-&gt;fieldLayoutId,
    'authorId' =&gt; 1,
    'title' =&gt; 'My Entry',
    'slug' =&gt; 'my-entry',
    'postDate' =&gt; new DateTime(),
]);

// Set the custom field values (including Matrix)
$entry-&gt;setFieldValues([
    'summary' =&gt; 'Some "summary" custom field value...',
    'matrixField' =&gt; [
        'new1' =&gt; [
            'type' =&gt; 'blockTypeHandle',
            'fields' =&gt; [
                // the block's custom field values...
            ],
        ],
        'new2' =&gt; [
            'type' =&gt; 'blockTypeHandle',
            'fields' =&gt; [
                // the block's custom field values...
            ],
        ],
    ],
]);

// Save the entry
Craft::$app-&gt;elements-&gt;saveElement($entry);