How to convert youtube embed code to url? - php

There are a lot of examples of how to convert a youtube url to embed code, but I need a reverse code. I was never successful with all those expressions, so my question is How can I convert an embed code to a URL ? Thanks in advance.

In PHP, you can do that with DOMDocument to get the src attribute of the iframe, and preg_replace() to convert it to the video url:
$embed = '<html><head></head><body><p>Hello, there is the video <iframe width="560" height="315" src="http://www.youtube.com/embed/K75a2k_6QWs" frameborder="0" allowfullscreen></iframe> what do you think?</p></body></html>';
$doc = new DOMDocument();
$doc->loadHTML($embed);
while($iframe = $doc->getElementsByTagName('p')->item(0)->getElementsByTagName('iframe')->item(0)) {
$url = preg_replace(
'~/embed/~',
'/watch?v=',
$iframe->getAttribute('src')
);
$iframe->parentNode->replaceChild(
$doc->createTextNode($url),
$iframe
);
}
echo $result = $doc->getElementsByTagName('p')->item(0)->nodeValue; //'Hello, there is the video http://www.youtube.com/watch?v=K75a2k_6QWs what do you think?'

Related

How to get html code from Wordpress post content?

I want to wrap decode all html tags from a post content in Wordpress.
like
<iframe src="https://www.facebook.com/plugins/video.php?href=https%3A%2F%2Fwww.facebook.com%2FRocketsAreCool%2Fvideos%2F1032994553496742%2F&show_text=0&width=560" width="560" height="315" style="border:none;overflow:hidden" scrolling="no" frameborder="0" allowTransparency="true" allowFullScreen="true">
When I try this code:
$query = new WP_Query(array('name'=>'example_topic'));
$post = $query->posts;
$text = htmlspecialchars_decode($post->content);
It works, but not closing the html tag because the tag was not originally closed in the encoded tags, so every thing comes after not showing in browser.

Regex to remove iframe with facebook but keeps youtube

I want to remove only iframe(and everyhing inside iframe)with facebook like above but to keep youtube iframe:
<iframe src="http://www.facebook.com/plugins/like.php?href=http%3A%2F%2Fwww.example.com%2F%3Fp%313098&layout=standard&show_faces=true&width=500&action=recommend&colorscheme=light" ></iframe>
To keep iframes from youtube:
<iframe width="640" height="360" src="https://www.youtube.com/embed/hiYtWYLEjlI?rel=0" frameborder="0" allowfullscreen></iframe>
I've this regex but it only remove
<\/*i(?:frame|layer)|l(?:ayer|ink)[^>]*+>
https://regex101.com/r/eM9eS3/5
Better take the xpath approach:
$xml = simplexml_load_string($your_html_string);
$iframes = $xml->xpath("//iframe[contains(#src, 'facebook.com')]");
And delete these:
for ($i=0;$i<count($iframes);$i++) {
$iframe = $iframes[$i];
unset($iframe[0][0]);
}
Your new XML looks like:
echo $xml->asXML();
As whole function:
function goAwayFacebook($html) {
$xml = simplexml_load_string($html);
$iframes = $xml->xpath("//iframe[contains(#src, 'facebook.com')]");
for ($i=0;$i<count($iframes);$i++) {
$iframe = $iframes[$i];
unset($iframe[0][0]);
}
return $xml->asXML();
}
$newhtml = goAwayFacebook($html);
So you are roughly trying to check if www.facebook.com is present in <ifram> or not. This can be achieved by using following regex.
Regex: (?=.*www\.facebook\.com.*)<iframe .*<\/iframe>
Explanation:
(?=.*www\.facebook\.com.*) checks for presence of www.facebook.com between the <iframe> tags.
Regex101 Demo

Get YouTube video id from embed iframe code

I want to get the YouTube video ID from YouTube embed code using preg_match or regex. For a example
<iframe width="560" height="315" src="//www.youtube.com/embed/0gugBiEkLwU?rel=0" frameborder="0" allowfullscreen></iframe>
I want to take the ID 0gugBiEkLwU
Can anyone tell me how to do this. Really appropriate your help.
Using this pattern with a capturing group should give you the string you want:
d\/(\w+)\?rel=\d+"
example: https://regex101.com/r/kH5kA7/1
You can use :
src="\/\/(?:https?:\/\/)?.*\/(.*?)\?rel=\d*"
Check Demo Here
Explanation :
I know this is pretty late, but I came up with something for people who might still be looking.
Since not all Youtube iframe src attributes end in "?rel=", and can sometimes end in another query string or end with a double quote, you can use:
/embed\/([\w+\-+]+)[\"\?]/
This captures anything after "/embed/" and before the ending double-quote/query string. The selection can include any letter, number, underscore and hyphen.
Here's a demo with multiple examples: https://regex101.com/r/eW7rC1/1
The below function will extract the youtube video id from teh all format of youtube urls,
function getYoutubeVideoId($iframeCode) {
// Extract video url from embed code
return preg_replace_callback('/<iframe\s+.*?\s+src=(".*?").*?<\/iframe>/', function ($matches) {
// Remove quotes
$youtubeUrl = $matches[1];
$youtubeUrl = trim($youtubeUrl, '"');
$youtubeUrl = trim($youtubeUrl, "'");
// Extract id
preg_match("/^(?:http(?:s)?:\/\/)?(?:www\.)?(?:m\.)?(?:youtu\.be\/|youtube\.com\/(?:(?:watch)?\?(?:.*&)?v(?:i)?=|(?:embed|v|vi|user)\/))([^\?&\"'>]+)/", $youtubeUrl, $videoId);
return $youtubeVideoId = isset($videoId[1]) ? $videoId[1] : "";
}, $iframeCode);
}
$iframeCode = '<iframe width="560" height="315" src="http://www.youtube.com/embed/0gugBiEkLwU?rel=0" frameborder="0" allowfullscreen></iframe>';
// Returns youtube video id
echo getYoutubeVideoId($iframeCode);

Pulling video thumbnail from TED embed code

I'm trying to pull out the video thumbnail from the TED video embed code. Why? Well, I'm using a WordPress theme that uses a custom field to handle video but the thumbnail function for that field isn't built for TED. I'm trying to re-jig it.
Here's the video thumbnail retrieval function (where YouTube and Vimeo are covered):
function woo_get_video_image($embed) {
$video_thumb = '';
/* Let's start by looking for YouTube, then Vimeo */
if ( preg_match( '/youtube/', $embed ) ) {
// YouTube - get the video code if this is an embed code (old embed)
preg_match( '/youtube\.com\/v\/([\w\-]+)/', $embed, $match);
// YouTube - if old embed returned an empty ID, try capuring the ID from the new iframe embed
if( !isset($match[1]) )
preg_match( '/youtube\.com\/embed\/([\w\-]+)/', $embed, $match);
// YouTube - if it is not an embed code, get the video code from the youtube URL
if( !isset($match[1]) )
preg_match( '/v\=(.+)&/',$embed ,$match);
// YouTube - get the corresponding thumbnail images
if( isset($match[1]) )
$video_thumb = "http://img.youtube.com/vi/".$match[1]."/0.jpg";
} else if ( preg_match( '/vimeo/', $embed ) ) {
// Vimeo - get the video thumbnail
preg_match( '#http://player.vimeo.com/video/([0-9]+)#s', $embed, $match );
if ( isset($match[1]) ) {
$video_id = $match[1];
// Try to get a thumbnail from Vimeo
$get_vimeo_thumb = unserialize(file_get_contents_curl('http://vimeo.com/api/v2/video/'. $video_id .'.php'));
$video_thumb = $get_vimeo_thumb[0]['thumbnail_large'];
}
}
// return whichever thumbnail image you would like to retrieve
return $video_thumb;
}
Here's a typical TED embed:
<iframe
src="http://embed.ted.com/talks/andy_puddicombe_all_it_takes_is_10_mindful_minutes.html"
width="560" height="315"
frameborder="0"
scrolling="no"
webkitAllowFullScreen mozallowfullscreen allowFullScreen>
</iframe>
And the TED API docs if that helps at all: http://developer.ted.com/API_Docs
I seem to be having trouble customizing the preg_match and/or $get_vimeo_thumb portions (at least that's what I think is going on). Basically, I'm learning this portion of PHP and it's bumpy.
you can try this
$source = 'http://www.ted.com/talks/andy_puddicombe_all_it_takes_is_10_mindful_minutes';
$tedJson = json_decode(file_get_contents('http://www.ted.com/talks/oembed.json?url='.urlencode($source)), TRUE);
pr($tedJson);
you will get the json in responce
I don't know what possessed me to answer this question, but here is a (tested working) quick and dirty. You'll probably want to throw some validation in there somewhere.. And if I were getting paid to do this it wouldn't be using file_get_contents and I'd probably use DOMDocument.
$embed = '<iframe
src="http://embed.ted.com/talks/andy_puddicombe_all_it_takes_is_10_mindful_minutes.html"
width="560" height="315"
frameborder="0"
scrolling="no"
webkitAllowFullScreen mozallowfullscreen allowFullScreen>
</iframe>';
function getThumbnail($embed){
preg_match("/src\=\"(.+)?\"/", $embed, $matches);
$uri = $matches[1];
preg_match("/posterUrl\s=\s\'(.+)?\'/", file_get_contents($uri), $matches);
echo $matches[1];
}
getThumbnail($embed);
We are taking the src of the iframe, getting the contents, and scrapping the JS embed variable to grab the image they use for the thumbnail.
Obviously you won't echo the output, and who knows if this is against their TOS. As a matter of fact I'd bet they at least wouldn't let you use this unless you kept the logo (which is not the case). Use at your own risk.

php trim away undesired texts

I have the following data in mysql database which is an iframe from u-tube:-
`<iframe width="560" height="315" src="http://www.youtube.com/embed/Om2fabTIKE4" frameborder="0" allowfullscreen></iframe>`
Nevertheless, in the php codes, a present phase is present for the above iframe, in which I just need Om2fabTIKE4 as the variable to be filled in.
I would like to ask, is there any way that I can trim away
<iframe width="560" height="315" src="http://www.youtube.com/embed/
and
frameborder="0" allowfullscreen></iframe>
Try this:
$html = '<iframe width="560" height="315" src="http://www.youtube.com/embed/Om2fabTIKE4" frameborder="0" allowfullscreen></iframe>';
$dom = new DOMDocument();
$dom->loadHTML($html);
$tags = $dom->getElementsByTagName('iframe');
foreach ($tags as $tag)
$link = explode('/',parse_url($tag->getAttribute('src'),PHP_URL_PATH));
var_dump($link[2]);
You can learn more about the DOMDocument class here.
Use str_replace to remove the text

Categories