如何从远程页面获取iframe内容? [英] How to get iframe content from a remote page?

查看:140
本文介绍了如何从远程页面获取iframe内容?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我认为PHP没用,因为在执行php之后插入iframe,或者我错了?

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

因此,我所知道的唯一解决方案是使用Javascript / jQuery。

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

例如如果JS与iframe在同一页面上,这将有效:

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>

但是我使用Simple HTML DOM库来抓取远程网页,如:

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();

但显然,没有返回任何内容;(因为在运行php之后会显示iframe;(

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>

在我抓取的页面的标题中存储在$ html中。

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

任何想法如何获取iframe内容,或者这种过于复杂的方法和一些更简单的解决方案存在?

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

推荐答案

您将无法使用javascript访问iframe内的远程页面文档原始政策。

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

如果你知道页面的URL,你可以使用PHP CURL来检索它

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);  

这篇关于如何从远程页面获取iframe内容?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆