How to get iframe content from a remote page?

user2405063 picture user2405063 · May 21, 2013 · Viewed 16.7k times · Source

I think PHP is useless, bacause iframe is inserted after php is executed, or am I wrong?

So, the only solution I am aware of is to use Javascript/jQuery.

E.g. this would work if the JS would be on the same page as a the iframe:

<html>
<head>
<title></title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.js"></script>
<script type="text/javascript">

  $(function() {
    var myContent = $("#iFrame").contents().find("#myContent")
  });

</script>
</head>
<body>
  <iframe src="mifile.html" id="iFrame" style="width:200px;height:70px;border:dotted 1px red" frameborder="0">
     <div id="myContent">
        iframe content blablabla
     </div>
  </iframe>
</body>
</html>

However I am using Simple HTML DOM library to grab the distant webpage like:

$url = 'http://page-with-some-iframe.com/';
            $html = file_get_html( $url );

            // Find iframes and put them in an array
            $iframes_arr = array();
            foreach($html->find('iframe') as $element) {
                $iframes_arr[] = $element->outertext;
            }
var_dump($iframes_arr);
die();

But obviously, nothing is returned ;(, because iframes are displayed after php is run ;(

So, I was thinking that I would probably need to inject this code:

<script type="text/javascript">

  $(function() {
    var myContent = $("#iFrame").contents().find("#myContent")
  });

</script>

in the header of my grabbed page stored in $html.

Any idea how to get iframe content like that or is this too complicated approach and some easier solution does exist?

Answer

michael picture michael · May 21, 2013

You won't be able to access the document of a remote page inside an iframe using javascript because of the same origin policy.

If you know the URL of the page you can use PHP CURL to retrieve it

<?php 
        // Initialise a cURL object
        $ch = curl_init(); 

        // Set url and other options
        curl_setopt($ch, CURLOPT_URL, "http://page-with-some-iframe.com");
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 

        // Get the page contents
        $output = curl_exec($ch); 

        // close curl resource to free up system resources 
        curl_close($ch);