3

Was just wondering if any of you guys know how to get all iframes src from html code in php? Would help me a lot!

I have tried this so far:

$dom = new DOMDocument();
$html = $data;

@$dom->loadHTML($html);

$a = $dom->getElementsByTagName('iframe');

for ($i; $i < $a->length; $i++) {
$attr = $a->item($i)->getAttribute('src');

echo $attr . "\n";
}

This is the URL: http://www.youtube.com/all_comments?v=wb1u5CeMhkI

And then I want to get the iframe src in the 'comments-iframe-container' div. Search for the div, and the iframe will be 2 lines below the div.

Have a lovely christmas! :)

11
  • 3
    Aaaaaaand what did you try so far? This is stackoverflow, not yahoo answers. Edit: all right, he wrote something now :) Commented Dec 20, 2013 at 17:07
  • Using something like simple_html_dom or DOM you can iterate through iframe elements and get the source. This is very basic if you look at the documentation. Commented Dec 20, 2013 at 17:08
  • 2
    Use a DOM parser (PHP's DOMDocument, for example) to achieve this. You can use foreach($dom->getElementsByTagName('iframe') as $iframe) { ... }. Commented Dec 20, 2013 at 17:09
  • @Anders: Where exactly do you have issues? What is not working? Commented Dec 20, 2013 at 17:10
  • indeed, as @AmalMurali said, you should loop through all 'iframe' objects of your DOMDocument. Anyway, what's going wrong with the output of your above code? It absolutely seems legit to me :) Commented Dec 20, 2013 at 17:11

1 Answer 1

0

The iframe you're trying to access is created dynamically via JavaScript. It doesn't exist when you try to load the html with PHP. Try loading the source of the page instead of looking at it in a console (firbug, etc) to see what I mean.

Off the top of my head I think you're going to have to execute the contents of that youtube page on your server as a browser would to get access to the iframe. That could involve crawling the page with PHP, then passing the source into something that will process the HTML/JavaScript, then passing the result back to PHP to get the SRC of the iframes.

I'm not aware of any out-of-the-box PHP solutions for this. Maybe the following SO links will get you started:

I feel like this isn't really a complete answer, but I'm not allowed to leave comments yet so sorry in advance.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.