Hello,

Any tips on saving a youtube video url programmatically?

I tried $node->set('video_field','url-of-video') but it does not work.

Comments

alexpiaz created an issue. See original summary.

deaom’s picture

Status: Active » Needs review

It is a little hacky solution, but it should work.

$data = file_get_contents('https://www.youtube.com/watch?v=Uh5mEat46fc');
$name = 'https://www.youtube.com/watch?v=Uh5mEat46fc';
$filename = substr($name, strpos($name, "=") + 1);
$file = file_save_data($data, 'public://' . $filename, FILE_EXISTS_REPLACE);
$file->setMimeType('video/youtube');
$file->setFileUri('youtube://' . $filename);

and then in the node create

Node::create([
   'type' => 'article',
   'title' => 'title of article',
   // the machine name of the embed video field
   'field_video_test_embed' => [
     'target_id' => $file->id(),
     'filename' => $filename,
    ],
])->save();
hypertext200’s picture

Status: Needs review » Fixed

Status: Fixed » Closed (fixed)

Automatically closed - issue fixed for 2 weeks with no activity.

leopathu’s picture

#2 Seems a good approach but have small correction in that.

Don't need to save real youtube data locally. Just save empty content as file then set mime type and fileUri will handle the rest of things.

importantly have save file finally.

<?php
$data = '';
$name = 'https://www.youtube.com/watch?v=Uh5mEat46fc';
$filename = substr($name, strpos($name, "=") + 1);
$file = file_save_data($data, 'public://' . $filename, FILE_EXISTS_REPLACE);
$file->setMimeType('video/youtube');
$file->setFileUri('youtube://' . $filename);
$file->save();
?>