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.
Asked
Active
Viewed 4,408 times
0
-
Take the src value from the iframe tag? – ka_lin Jan 04 '15 at 13:39
-
http://stackoverflow.com/questions/8536787/strip-youtube-embed-code-down-to-url-only – ka_lin Jan 04 '15 at 13:41
-
I edited my answer, it should work now – Jonan Jan 04 '15 at 13:56
1 Answers
0
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?'

Jonan
- 2,485
- 3
- 24
- 42
-
Sorry, I have not mentioned, that there is some content around embed code and it must remain – Mindaugas Jakubauskas Jan 04 '15 at 13:59
-
@MindaugasJakubauskas so, do you just want to replace the iframe(s) with the video urls? Can you give an example of the string you need to get the url from and an example result string? – Jonan Jan 04 '15 at 14:03
-
The example would be "Hello, there is the video *iframe* what do you think?" and the result should be "Hello, there is the video *video url* what do you think?" :) – Mindaugas Jakubauskas Jan 04 '15 at 14:08
-
everything works great, but somewhy I get all those http headers, how could I get rid of it? (I am using ajax $_POST, I know $_GET doesn't send those, but it is not really possible in my code.. ) – Mindaugas Jakubauskas Jan 04 '15 at 14:25
-
@MindaugasJakubauskas What http headers do you mean? And are you sending the text with the `iframes` to `php` using `Ajax` to get them converted? If so, you could probably better convert them using `javascript` instead of using `Ajax` requests – Jonan Jan 04 '15 at 14:28
-
, no I'm sending it to write into database, convertion is just a little part of my code. – Mindaugas Jakubauskas Jan 04 '15 at 14:29
-
@MindaugasJakubauskas so if I get you right, you only want to parse the `HTML` inside the first `
` tag of the `body`?
– Jonan Jan 04 '15 at 14:31 -
@MindaugasJakubauskas it will now only parse and return the contents of the first `p` element in the `body` – Jonan Jan 04 '15 at 14:41