Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get html tag from string in php?

Tags:

html

dom

php

iframe

I have a html output I'm pulling from a RSS feed, it is somethig like this:

<div>
    <p>
        Some text
    </p>
    <iframe src="http://www.source.com"></iframe>
</div>

The problem is that I only need the attr "src" of the iframe tag, Is there a way to get it with PHP? Regex maybe?

Thanks in advance!

like image 439
Javier Villanueva Avatar asked Oct 21 '25 05:10

Javier Villanueva


1 Answers

If you're consistently getting just the data you listed above, you could use a simple substring, using the string positions of src=" and "><iframe to specify which substring you want:

$html = '<div><p>Some text</p><iframe src="http://www.source.com"></iframe></div>';

$start = strpos($html, 'src="') + 5;
$length = strpos($html, '"></iframe') - $start;
$src = substr($html, $start, $length);

echo $src;

EDIT - fixed the code and split into multiple lines. This could easily be a one-liner, but - thought it was easier to understand if I broke into multiple lines.

like image 126
Dave Avatar answered Oct 23 '25 20:10

Dave